Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q4 of 15
Java - Encapsulation

What will be the output of the following 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.name);
}
}
ACompilation error
BAlice
Cnull
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze access to private variable

    The variable 'name' is private in Person class, so it cannot be accessed directly outside the class.
  2. Step 2: Check the print statement

    System.out.println(p.name); tries to access private variable directly, causing a compilation error.
  3. Final Answer:

    Compilation error -> Option A
  4. Quick Check:

    Private variables cannot be accessed directly outside class [OK]
Quick Trick: Private variables cause compile error if accessed directly [OK]
Common Mistakes:
  • Assuming private variables print their value directly
  • Thinking it prints null by default
  • Expecting runtime error instead of compile error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes