The ==
and !=
operators are binary operators that evaluate to true
or false
depending on whether the operands are equal. The ==
operator gives true
if the operands are equal and false
otherwise. The !=
operator gives false
if the operands are equal and true
otherwise.
These operators can be used operands with primitive and reference types, but the behavior is significantly different. According to the JLS, there are actually three distinct sets of these operators:
==
and !=
operators.==
and !=
operators.==
and !=
operators.However, in all cases, the result type of the ==
and !=
operators is boolean
.
==
and !=
operatorsWhen one (or both) of the operands of an ==
or !=
operator is a primitive numeric type (byte
, short
, char
, int,
long
, float
or double
), the operator is a numeric comparison. The second operand must be either a primitive numeric type, or a boxed numeric type.
The behavior other numeric operators is as follows:
byte
, short
or char
, it is promoted to an int
.- If the promoted operands are `int` or `long` then the values are tested to see if they are identical.
- If the promoted operands are `float` or `double` then:
- the two versions of zero (`+0.0` and `-0.0`) are treated as equal
- a `NaN` value is treated as not equals to anything, and
- other values are equal if their IEEE 754 representations are identical.
Note: you need to be careful when using ==
and !=
to compare floating point values.
==
and !=
operatorsIf both operands are boolean
, or one is boolean
and the other is Boolean
, these operators the Boolean ==
and !=
operators. The behavior is as follows:
Boolean
, it is unboxed.A | B | A == B | A != B | —— | —— | —— | —— | false | false | true | false | false | true | false | true | true | false | false | true | true | true | true | false |