Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Constructors
What will be the output of this code?
class Person {
  String name;
}
public class Test {
  public static void main(String[] args) {
    Person p = new Person();
    System.out.println(p.name);
  }
}
Anull
B"" (empty string)
CCompilation error
DRuntime exception
Step-by-Step Solution
Solution:
  1. Step 1: Understand default constructor and field initialization

    Java provides a default constructor. The String field 'name' is initialized to null by default.
  2. Step 2: Predict output of printing name

    Printing p.name outputs null because object references default to null.
  3. Final Answer:

    null -> Option A
  4. Quick Check:

    Default String field value = null [OK]
Quick Trick: Object fields default to null if not initialized [OK]
Common Mistakes:
  • Expecting empty string
  • Thinking compile error due to missing constructor
  • Expecting runtime exception

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes