Lesson: Comparison

Explore comparing variable values and making decisions based on the results.

Understand what comparison is, what the Java comparsion operators are and how to use them.


A simple program, like Hello World, just flows from start to finish, one statement after another until done. Solving real problems always involves evaluating data or user input and making decisions about what to do next, when to do it and what to do when things go wrong and much more. Handling these possibilities is called Flow Control.

Flow control is based on comparison. This means taking two variables and comparing them resulting in a boolean (true/false) value. We then use that boolean result to decide what to do next in a flow control statement.

Comparison is taking two values separated by a comparison operator and replacing them (internally) with the boolean result of the comparison. For instance, if  X = 5 and Y = 5, then the comparison  X == Y  results in true. Remember that = by itself is not comparison, it is assignment. Compare equal is ==.  Using X from above,  X == 7  results in false. The Not equal comparison operator is !=, so  X != 7  results in true.

Java supports an extensive list of comparison operators. Here is a detailed discussion of comparison operators. Note that comparison operators are divided into several types. Relational operators are used when you are comparing two non-boolean values. When comparing boolean values, the operators are called conditional. There are also bitwise operators but we will leave that for you to investigate in the resources noted earlier in this paragraph.

Relational operators are pretty easy to understand, the two values (also called operands) are compared and are either equal or not equal, with not equal split into greater or less than. Conditional operators are different. When we have two boolean values, we can AND (&& operator) them, meaning if both values are true, the result is true. If either value is false, the result is false. We can also OR (II operator) the values, meaning if either value is true, the result is true.

Watch these videos (video1, video2, video3, video4) for more information.

The ! operator prefixed to a boolean inverts the value of the boolean. Thus (from above) if  X == Y is true, !( X == Y) is false. If we have a boolean variable, B equal to true, then B by itself evaluates to true, but !B evaluates to false.

Comparison can be combined with parenthesis:  ( X == 5 ) && ( Y > 3 )  results in true, since both terms are true and then they are and'ed together in a third comparison. By the same token, ( X == 5 ) && ( Y != X ) results in false, since one term is true and one is false

Click Next for a quiz on comparsions.