Bird
0
0

What will be the output of this Java code?

medium📝 Predict Output Q4 of 15
Java - Constructors

What will be the output of this Java code?

class Car {
  String model;
  int year;
  Car(String m, int y) {
    model = m;
    year = y;
  }
  void display() {
    System.out.println(model + " " + year);
  }
}
public class Test {
  public static void main(String[] args) {
    Car c = new Car("Toyota", 2020);
    c.display();
  }
}
ACompilation error
Bnull 0
CToyota 2020
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze constructor call

    Car object is created with model "Toyota" and year 2020 using parameterized constructor.
  2. Step 2: Check display method output

    display() prints model and year separated by space, so output is "Toyota 2020".
  3. Final Answer:

    Toyota 2020 -> Option C
  4. Quick Check:

    Parameterized constructor sets fields = Output correct [OK]
Quick Trick: Constructor sets fields, display prints them [OK]
Common Mistakes:
  • Expecting default values instead of assigned ones
  • Thinking code causes errors
  • Confusing method call syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes