Incremental Java
Equality Operators

Checking for Equality

It's common in many programming languages to want to find out whether two expressions have the same value. Java has operators for checking equality and inequality.

Equality

The equality operator is == (two consecutive equal signs).

It is a binary operator: exprleft == exprright.

Java requires that the left and right expression evaluate to the same (or compatible) types. Thus, if the left expression has type int, the right must as well. (Actually, this isn't entirely true---we'll discuss this in the lesson on mixed type expressions. For now, pretend it's true).

Since we haven't talked about objects yet, this equality check is primitive type equality, which compares the values in the boxes, just as we expect.

== evaluates to a boolean value.

Here's the chart that summarizes the behavior of the == operator.

Subevaluations Result
EVAL[ exprleft ] == EVAL[ exprright ] EVAL[ exprleft == exprright ] = true
EVAL[ exprleft ] != EVAL[ exprright ] EVAL[ exprleft == exprright ] = false

This just says that if the left and right operand evaluate to the same value, == evaluates to true, otherwise it evaluates to false.

Notice I write == within the EVAL function and outside it. When it's inside, it refers to Java's == operator. When it's outside, it refers to mathematical equality. It can be hard to distinguish the Java symbols from the metasymbol.

Inequality

The inequality operator is != (an exclamation point, followed by an equal sign).

It is a binary operator: exprleft != exprright.

Again, both operands should evaluate to values of compatible types.

We can write exprleft != exprright equivalently as ! ( exprleft == exprright ).

In other words, it's just the negation of the equality operator. Thus, given the same left and right operand, the equality operator and inequality operator evaluate to opposite truth values (one evaluates to true while the other evaluates to false, and vice versa).

Here's the chart that describes the behavior of the inequality operator.

Subevaluations Result
EVAL[ exprleft ] != EVAL[ exprright ] EVAL[ exprleft != exprright ] = true
EVAL[ exprleft ] == EVAL[ exprright ] EVAL[ exprleft != exprright ] = false