Bird
0
0

Consider the following Java code:

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

Consider the following Java code:

class Light {
    boolean isOn = false;
    void toggle() {
        isOn = !isOn;
    }
    boolean status() {
        return isOn;
    }
}

class Room {
    Light light = new Light();
    void switchLight() {
        light.toggle();
    }
    boolean lightStatus() {
        return light.status();
    }
}

public class Main {
    public static void main(String[] args) {
        Room room = new Room();
        System.out.println(room.lightStatus());
        room.switchLight();
        System.out.println(room.lightStatus());
    }
}

What is the output when this program runs?

Afalse true
Btrue false
Cfalse false
Dtrue true
Step-by-Step Solution
Solution:
  1. Step 1: Check initial light status

    Initially, isOn is false, so room.lightStatus() prints false.
  2. Step 2: Toggle light and check status again

    Calling room.switchLight() toggles isOn to true. Then room.lightStatus() prints true.
  3. Final Answer:

    false true -> Option A
  4. Quick Check:

    Initial false, toggled true = false then true [OK]
Quick Trick: Track boolean changes step-by-step [OK]
Common Mistakes:
  • Assuming toggle sets true first without initial check
  • Confusing method calls and variable values
  • Ignoring initial value of isOn

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes