Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q13 of 15
Java - Encapsulation
What will be the output of the following code?
public class Person {
  private String name;
  public String getName() { return name; }
  public void setName(String name) { this.name = name; }
  public static void main(String[] args) {
    Person p = new Person();
    p.setName("Alice");
    System.out.println(p.getName());
  }
}
AAlice
Bnull
CCompilation error
DEmpty line
Step-by-Step Solution
Solution:
  1. Step 1: Trace the setter method call

    The setName method sets the private variable name to "Alice".
  2. Step 2: Trace the getter method call

    The getName method returns the value of name, which is now "Alice".
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Setter sets "Alice", getter returns "Alice" [OK]
Quick Trick: Setter sets value, getter returns it [OK]
Common Mistakes:
  • Expecting null because variable is private
  • Thinking code causes compilation error
  • Assuming output is empty line

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes