Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Classes and Objects
What will be the output of this code?
class Light {
  boolean isOn = false;
  void switchOn() {
    isOn = true;
  }
  void printStatus() {
    System.out.println(isOn);
  }
}
public class Test {
  public static void main(String[] args) {
    Light l1 = new Light();
    Light l2 = new Light();
    l1.switchOn();
    l2.printStatus();
  }
}
Afalse
Btrue
CCompilation error
DRuntime exception
Step-by-Step Solution
Solution:
  1. Step 1: Understand object states

    Two Light objects are created: l1 and l2. Initially, isOn is false for both.
  2. Step 2: Method calls

    l1.switchOn() sets l1.isOn to true. l2.printStatus() prints l2.isOn, which remains false.
  3. Final Answer:

    false -> Option A
  4. Quick Check:

    Each object has its own state; changing one doesn't affect another. [OK]
Quick Trick: Each object has independent instance variables. [OK]
Common Mistakes:
  • Assuming l2.isOn changes when l1.isOn changes
  • Confusing instance variables as shared

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes