Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
For an ordinary Java boolean, toggle its value with flag = !flag;. The ! operator reverses the current value: true becomes false, and false becomes true. If the flag can be null or is shared across threads, use a different approach.
The simplest Java boolean toggle
Java’s primitive boolean has two values, true and false. The logical complement operator ! produces the opposite value, so assign that result back to the variable:
boolean enabled = false;
enabled = !enabled;
System.out.println(enabled); // true
enabled = !enabled;
System.out.println(enabled); // false
The right-hand expression is evaluated first, then assigned to enabled. This is shorter and clearer than spelling out an if/else for a simple inversion:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →if (enabled) {
enabled = false;
} else {
enabled = true;
}
The language specification defines the boolean values and logical complement operator in the Java SE 25 Java Language Specification.
Encapsulate a toggle in a method
If a class owns the state, keep its field private and expose an operation to invert it. Offer a separate setter for callers that know the desired state:
public final class FeatureSwitch {
private boolean enabled;
public boolean isEnabled() {
return enabled;
}
public void toggle() {
enabled = !enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Now toggle() means “invert the current value,” while setEnabled(true) means “make the value true.” Use names such as enable() and disable() when callers should not need to know the current state.
A toggle method may return the new value when that is useful:
public boolean toggle() {
enabled = !enabled;
return enabled; // the value after toggling
}
Document that contract. A boolean return could otherwise be mistaken for the previous value or for an indication that the operation succeeded.
Rank #2
Toggle or set? Choose based on the caller’s intent
A toggle is not idempotent: applying it twice undoes the first change. That is often exactly right for a local button or keyboard action:
public void onToggleRequested() {
enabled = !enabled;
updateUi();
}
But if an event, network message, or command can be retried or delivered more than once, a repeated toggle may leave the state wrong. When the caller knows the intended state, prefer an explicit assignment such as setEnabled(desiredValue). For a UI action, update dependent presentation after changing the state, as in statusLabel.setText(enabled ? "Enabled" : "Disabled"). Java itself does not define one universal event-handler API; Swing, JavaFX, Android, and server frameworks have different callback conventions.
!flag versus flag ^= true
Boolean XOR also reverses a value when the other operand is true:
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsflag ^= true; // equivalent toggle
For a simple state change, flag = !flag; is more recognizable and usually easier to read. Use XOR when it is part of a broader XOR or parity expression, not just to make a boolean toggle.
Toggling a nullable Boolean
Boolean is the wrapper object for primitive boolean and can also hold null. The expression !enabled requires a primitive, so Java unboxes the wrapper. If the value is null, unboxing throws NullPointerException:
Boolean enabled = null;
enabled = !enabled; // NullPointerException
Choose the null policy according to what null means in your application:
- Treat null as false:
enabled = !Boolean.TRUE.equals(enabled);This mapsnulltotrue,truetofalse, andfalsetotrue. It intentionally collapses null into the false case before inversion. - Reject null: use
Objects.requireNonNull(value, "value must not be null")before unboxing and inverting. This is appropriate when missing data is invalid. - Preserve unknown as a distinct state: use an explicit type, such as an enum with
ENABLED,DISABLED, andUNKNOWN. A boolean toggle cannot represent all three meanings without an extra policy.
Prefer primitive boolean when the state is always binary. Use Boolean when nullability is meaningful, such as for an omitted configuration value or nullable database column, or when an object is required by a generic API. The Java SE 25 Boolean API documents the wrapper and its value-based behavior; its constructors have been deprecated since Java 9, so do not create wrappers with new Boolean(...).
Thread-safe toggling: visibility is not atomicity
If a flag is confined to one thread, enabled = !enabled; is sufficient. If multiple threads may invert the same shared flag, that expression is a read-modify-write sequence: a thread reads the value, negates it, and writes the result. Two threads can read the same old value and both write the same opposite value, losing one logical toggle.
Rank #4
Declaring the field volatile does not fix that race:
private volatile boolean enabled;
public void toggle() {
enabled = !enabled; // still not an atomic toggle
}
volatile provides visibility and ordering guarantees for individual reads and writes, but it does not make the entire read-negate-write operation atomic. It can suit a flag where one thread publishes an explicit value and other threads observe it, such as a shutdown request set to true. It is not enough when concurrent writers must each invert the value. The Java SE 25 VarHandle documentation distinguishes volatile access modes from atomic update operations.
Use synchronization when the state belongs under a lock
public final class SafeToggle {
private boolean enabled;
public synchronized boolean toggle() {
enabled = !enabled;
return enabled;
}
public synchronized boolean isEnabled() {
return enabled;
}
}
The read, inversion, and write happen while holding the object’s monitor. Keep reads and writes that participate in this thread-safety policy under the same lock. Synchronization is often the clearest choice if the toggle must change alongside other fields or preserve a larger invariant.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Use AtomicBoolean for one independently updated flag
AtomicBoolean provides atomic operations on a single boolean value, but it has no dedicated portable toggle() method. Use compare-and-set in a loop:
Best Value
import java.util.concurrent.atomic.AtomicBoolean;
private final AtomicBoolean enabled = new AtomicBoolean(false);
public boolean toggle() {
boolean current;
boolean next;
do {
current = enabled.get();
next = !current;
} while (!enabled.compareAndSet(current, next));
return next;
}
The loop reads a candidate value and attempts to replace it only if the value is still what it read. If another thread changed it first, compareAndSet fails and the loop retries from the latest value. By contrast, this is still unsafe for competing toggles:
enabled.set(!enabled.get()); // separate read and write; updates can be lost
See the Java SE 25 AtomicBoolean API for its atomic operations and compare-and-set behavior. Atomic classes are useful for individual variables; they do not make changes to multiple fields a single transaction. When several values must remain consistent together, protect the whole operation with synchronization or a lock.
Parsing boolean text is not toggling
When a value comes from text, parsing and inversion are separate operations. Boolean.parseBoolean(text) returns true only when the non-null string equals "true" ignoring case; other inputs, including null, yield false. If invalid text should be reported rather than silently interpreted as false, validate it before relying on that method.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
boolean enabled = Boolean.parseBoolean(text);
Boolean.getBoolean(name) does something different: it reads the system property whose name is name, then returns true only if that property’s value equals "true" ignoring case. It does not parse the argument itself as a boolean. For example, Boolean.getBoolean("feature.enabled") looks up the system property named feature.enabled. Both methods are documented in the Java SE 25 Boolean API.
Test both directions and the toggle contract
For a reusable state class, test both starting values and verify that two toggles restore the original value:
@Test
void toggleInvertsFalseToTrue() {
ToggleState state = new ToggleState(false);
state.toggle();
assertTrue(state.isOn());
}
@Test
void toggleInvertsTrueToFalse() {
ToggleState state = new ToggleState(true);
state.toggle();
assertFalse(state.isOn());
}
@Test
void twoTogglesRestoreOriginalState() {
ToggleState state = new ToggleState(false);
state.toggle();
state.toggle();
assertFalse(state.isOn());
}
The useful property is toggle(toggle(x)) == x for either primitive boolean value. Also test initial-state behavior, explicit set followed by toggle, and the return value if the method returns one. If the class claims to support concurrent use, test that behavior under concurrency as well; otherwise make its single-threaded ownership clear.
Quick Recap
Quick decision guide
| Situation | Use |
|---|---|
| Ordinary local or single-threaded primitive state | flag = !flag; |
| State owned by a class | A private field with toggle() and an explicit setter |
| Caller supplies the desired value or commands may be retried | setEnabled(desiredValue), not a toggle |
| Nullable value | Define whether null means false, invalid, or unknown before changing it |
| One writer publishes explicit updates for readers | Consider volatile for visibility, if that is the complete access pattern |
| Several threads invert one independent flag | AtomicBoolean with compare-and-set, or synchronization |
| Flag must change with other fields | Synchronization or a lock around the shared invariant |
| True, false, and unknown are all meaningful | An enum or another explicit multi-state type |
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Recommended Free Tools

