Mutator Methods

AP Computer Science A· difficulty 2/5

public class Switch {
    private boolean on;
    public void toggle() { on = !on; }
    public boolean isOn() { return on; }
}
// ...
Switch s = new Switch();
s.toggle(); s.toggle(); s.toggle();
System.out.println(s.isOn());

What is printed?

  • A

    Compile-time error

  • B

    false

  • C

    1

  • D

    true

    check_circle

Explanation

Starting from false: toggle to true, toggle to false, toggle to true. Final value true.

Want 10 more like this — adaptive to your weak spots?

Related questions