Post

Created by @nathanedwards
 at October 31st 2023, 6:09:26 pm.

Question:

Consider the following code:

public class Car {
    private String make;
    private String model;
    private int year;

    public Car() {
        make = "Unknown";
        model = "Unknown";
        year = 0;
    }

    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public int getYear() {
        return year;
    }

    public static void main(String[] args) {
        Car car1 = new Car();
        Car car2 = new Car("Toyota", "Camry", 2021);

        System.out.println("Car 1 make: " + car1.getMake());
        System.out.println("Car 1 model: " + car1.getModel());
        System.out.println("Car 1 year: " + car1.getYear());

        System.out.println("Car 2 make: " + car2.getMake());
        System.out.println("Car 2 model: " + car2.getModel());
        System.out.println("Car 2 year: " + car2.getYear());
    }
}

What will be the output of the above code?

A) Car 1 make: Unknown Car 1 model: Unknown Car 1 year: 0 Car 2 make: Toyota Car 2 model: Camry Car 2 year: 2021

B) Car 1 make: Unknown Car 1 model: Unknown Car 1 year: 0 Car 2 make: Toyota Car 2 model: Camry Car 2 year: 0

C) Car 1 make: Toyota Car 1 model: Camry Car 1 year: 2021 Car 2 make: Unknown Car 2 model: Unknown Car 2 year: 0

D) Compilation error

Answer:

A) Car 1 make: Unknown Car 1 model: Unknown Car 1 year: 0 Car 2 make: Toyota Car 2 model: Camry Car 2 year: 2021

Explanation:

  1. The Car class has two constructors: a default constructor and a parameterized constructor.
  2. The default constructor initializes the instance variables make as "Unknown", model as "Unknown", and year as 0.
  3. The parameterized constructor takes three parameters (make, model, and year) and assigns the values to the respective instance variables.
  4. In the main method, two Car objects are instantiated: car1 using the default constructor and car2 using the parameterized constructor with values "Toyota", "Camry", and 2021.
  5. The output will be printed using the System.out.println statements.
  6. car1 was created using the default constructor, so its make, model, and year will be set to their default values, which are "Unknown", "Unknown", and 0 respectively.
  7. car2 was created using the parameterized constructor, so its make, model, and year will be set to the specified values, which are "Toyota", "Camry", and 2021 respectively.
  8. Therefore, the correct answer is option A.