Bird
0
0

What will be the output of the following Java code?

medium📝 Predict Output Q13 of 15
Java - Encapsulation
What will be the output of the following Java code?
class Person {
  private String name = "Alice";
  public String getName() {
    return name;
  }
}

public class Test {
  public static void main(String[] args) {
    Person p = new Person();
    System.out.println(p.getName());
  }
}
Anull
BCompilation error
CAlice
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand private variable access

    The variable name is private but accessed via the public getter getName().
  2. Step 2: Trace the output

    The getter returns "Alice", so System.out.println prints "Alice".
  3. Final Answer:

    Alice -> Option C
  4. Quick Check:

    Getter returns private value = Alice [OK]
Quick Trick: Private data accessed via public getter returns value [OK]
Common Mistakes:
  • Expecting direct access to private variable
  • Thinking code causes compilation error
  • Confusing output with null or error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes