Problem of the Day
Thursday, March 5, 2026
Problem:
The Bit class represents a binary digit that is either "on" or "off"—the boolean instance variable on is set to true then the bit is on, and false when the bit is off. A partial class description is given here.
public class Bit
{
private boolean on;
public Bit()
{
on = false;
}
/**
* Changes the state of the switch
* @return the new state of the switch.
*/
public boolean flip()
{
/* missing code */
}
}
The boolean method flip is intended to change the state of on to its opposite state, and return the new value of on. Which of the following could be used to replace /* missing code */ so that the method works correctly?
if (on)
on = false;
else
on = true;
return on;if (on)
return false;
else
return true;on = !on;
return on;
- I only
- I and II only
- II and III only
- I and III only
- I, II, and III
The correct answer is d. Code snippet II returns the opposite value, but doesn't actually change the value of on before doing so.
The shortest way of flipping the bit and reporting its new state would be this method:
public boolean flip()
{
return on = !on;
}
This solution takes advantage of the fact that an assignment operator in Java returns the result of the assignment as part of that process. (This fact isn't typically covered in the AP Computer Science A curriculum.)