Bird
0
0

What will be printed when the following Java code is executed?

medium📝 Predict Output Q4 of 15
Java - Packages and Access Control
What will be printed when the following Java code is executed?
class Sample {
  private String message = "Hello";
  public void showMessage() {
    System.out.println(message);
  }
}
public class Main {
  public static void main(String[] args) {
    Sample s = new Sample();
    s.showMessage();
  }
}
Anull
BHello
CCompilation error
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand private variable access

    The private variable message is accessed inside the class method showMessage(), which is allowed.
  2. Step 2: Execution flow

    The main method creates an instance and calls showMessage(), printing the value of message.
  3. Final Answer:

    Hello -> Option B
  4. Quick Check:

    Private accessible inside class methods [OK]
Quick Trick: Private accessible within class methods [OK]
Common Mistakes:
  • Assuming private variables cannot be accessed even inside the class
  • Expecting compilation errors due to private modifier

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes