Bird
0
0

What will be the output of the following Java code?

medium📝 Predict Output Q13 of 15
Java - Packages and Access Control
What will be the output of the following Java code?
class Test {
  private int number = 5;
  public void printNumber() {
    System.out.println(number);
  }
}
public class Main {
  public static void main(String[] args) {
    Test t = new Test();
    t.printNumber();
  }
}
ARuntime error
BCompilation error
C0
D5
Step-by-Step Solution
Solution:
  1. Step 1: Understand private member access inside class

    The variable number is private but accessed inside its own class method printNumber(), which is allowed.
  2. Step 2: Check main method output

    The main method creates an object and calls printNumber(), which prints the value 5.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    Private accessible inside class method [OK]
Quick Trick: Private fields can be used inside their own class methods [OK]
Common Mistakes:
  • Thinking private prevents access even inside class
  • Expecting compilation error due to private
  • Confusing default value with actual initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes