Java's Relational Operators

These operators return a boolean result true or false.

> greater than
> less than
>= greater than or equal to
<= less than or equal to
== equal to
!= not equal to

Only the last two can be used in expressions relating boolean variables. The prefix operator ! means 'not'. It inverts a boolean result of what immediately follows it.

These operators return a boolean value indicating whether a particular relationship between two variables is true or false.

For example, in the test: if(x < y) Java evaluates the expression x < y as a behind-the-scenes boolean variable b whose value is either true or false. It then uses the value of b in the implied statement if(b == true) to determine which route to take.

Test boolean values directly:

If x and y are boolean variables use a test of the form: if(x || !y ){ ... }
instead of: if(x == true || y == false){ ... }

Single expressions which evaluate to a boolean value can be joined to form a composite expression using: && (conditional AND) and||(conditional OR). For example:

if( x && y ) { ... }
Java evaluates as little as it has to in order to obtain a valid result. For instance, in
if(i >= 0 && i < a.length && a[i] != 0){ ... }
if i is negative, the other two expressions are not evaluated.

Because == and != can only relate boolean values, they can be used to construct an exclusive OR or XOR test as follows:

if(x < 0 == y < 0)
  SameSign();
else
  DiffSign();
x != NaN always returns true
x # NaN always returns false where # is any relational operator other than !=.

If s1 and s2 are string pointers, the expression s1 == s2 is true only if s1 and s2 point to the same string array: it does not test to see if two different string arrays have the same content.


This page's parent within this Web Site. About this Web Site. Its home page. Email its Author.