Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Logical NOT operator !

The unary ! operator reverses a logical value: true becomes false, and false becomes true. It accepts boolean or Boolean and produces boolean. Applying it to a Boolean whose value is null throws NullPointerException.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

!expression

Write ! before its operand: !expression. It reverses a logical value: !true produces false, and !false produces true. The operator itself does not assign the result to a variable, so reading !ready does not change ready.

The operand must have type boolean or Boolean; the result always has type boolean. Numbers, strings, and other objects are not automatically treated as true or false: for example, !0 is a compile-time error.

For Boolean, Java automatically unboxes the operand to boolean. If the operand is null, unboxing throws NullPointerException before a negation result is produced. If null should mean not enabled, use !Boolean.TRUE.equals(enabled) instead of !enabled.

Parentheses determine the scope of negation: !ready || enabled means (!ready) || enabled, whereas !(ready || enabled) negates the result of the entire combined condition. Do not confuse ! with the comparison operator != or the integer bitwise complement operator ~.

Examples

public class LogicalNotDemo {
    public static void main(String[] args) {
        boolean ready = false;
        Boolean enabled = Boolean.TRUE;
        System.out.println(!ready);
        System.out.println(!enabled);
        System.out.println(!(ready || enabled));
        System.out.println(ready);
    }
}

Result

true
false
false
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources