Bird
0
0

What will be the output of this Java code?

medium📝 Predict Output Q4 of 15
Java - Encapsulation
What will be the output of this Java code?
class Box {
  private int size = 5;
  public int getSize() {
    return size;
  }
}
public class Test {
  public static void main(String[] args) {
    Box b = new Box();
    System.out.println(b.getSize());
  }
}
ARuntime error
B0
C5
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand private member access

    The variable size is private but accessed via the public method getSize(), which returns 5.
  2. Step 2: Trace the program output

    The main method creates a Box object and prints the value returned by getSize(), which is 5.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    Private accessed via public method = 5 [OK]
Quick Trick: Private accessed via public getter works [OK]
Common Mistakes:
  • Expecting direct access to private variable
  • Thinking private causes compile error here
  • Confusing default value with assigned value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes