Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Inequality operator !=

The != operator returns boolean: it compares numeric or boolean values, while for references it tests object identity rather than contents.

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

Syntax

left != right

left != right is equivalent to !(left == right) and returns boolean. Not every pair of types can be compared; invalid combinations cause a compile-time error.

Numbers are compared after binary numeric promotion. For boolean values, the result is true when the values differ. A numeric comparison involving NaN yields true; 0.0 != -0.0 yields false.

For compatible reference types, != tests identity: distinct objects can have equal contents. a != null checks for a non-null reference. For inequality according to equals, with null handling, use !Objects.equals(a, b).

Two wrapper operands, such as Integer, are compared as references. Comparison with a primitive may require unboxing; unboxing null throws NullPointerException.

Examples

import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        String a = new String("Java");
        String b = new String("Java");
        System.out.println(3 != 4);
        System.out.println(true != false);
        System.out.println(a != b);
        System.out.println(!Objects.equals(a, b));
        System.out.println(a != null);
    }
}

Result

true
true
true
false
true

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