Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Java - Classes and Objects
What will be the output of this code?
class Cat {
  String name = "Whiskers";
}

public class Main {
  public static void main(String[] args) {
    Cat c = new Cat();
    System.out.println(c.name);
  }
}
ARuntime error
BWhiskers
CCompilation error
Dnull
Step-by-Step Solution
Solution:
  1. Step 1: Understand object creation and field access

    The class Cat has a field name initialized to "Whiskers". Creating an object sets this field.
  2. Step 2: Print the field value

    The main method creates a Cat object and prints c.name, which outputs "Whiskers".
  3. Final Answer:

    Whiskers -> Option B
  4. Quick Check:

    Object field access prints initialized value [OK]
Quick Trick: Object fields print their assigned values [OK]
Common Mistakes:
  • Expecting null if not initialized
  • Thinking of compilation or runtime errors
  • Confusing field with method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes