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.size);
  }
}
ACompilation error
B0
CRuntime error
D5
Step-by-Step Solution
Solution:
  1. Step 1: Analyze access to private variable

    The variable 'size' is private and cannot be accessed directly outside the class.
  2. Step 2: Check code for direct access

    The code tries to print 'b.size' directly, which causes a compilation error.
  3. Final Answer:

    Compilation error -> Option A
  4. Quick Check:

    Accessing private variable directly = Compilation error [OK]
Quick Trick: Private variables can't be accessed directly outside class [OK]
Common Mistakes:
  • Assuming private variables can be printed directly
  • Expecting runtime error instead of compile error
  • Confusing default values with access errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes