Bird
0
0

What will be printed when this code runs?

medium📝 Predict Output Q5 of 15
Java - Classes and Objects

What will be printed when this code runs?

class Light {
  boolean isOn = false;
  void toggle() { isOn = !isOn; }
  void show() { System.out.println(isOn ? "On" : "Off"); }
}
public class Test {
  public static void main(String[] args) {
    Light light = new Light();
    light.show();
    light.toggle();
    light.show();
  }
}
AOn On
BOff On
COff Off
DOn Off
Step-by-Step Solution
Solution:
  1. Step 1: Check initial state

    Light starts with isOn = false, so first show() prints "Off".
  2. Step 2: Toggle and show again

    toggle() flips isOn to true, so second show() prints "On".
  3. Final Answer:

    Off On -> Option B
  4. Quick Check:

    Toggle changes state, output = Off then On [OK]
Quick Trick: Toggle flips boolean, changing output [OK]
Common Mistakes:
  • Assuming initial state is On
  • Not flipping boolean correctly
  • Expecting same output twice

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes