Lesson: Comparison

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

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

Content: 

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. 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. Watch this video and read the sections on comparison, logical and bitwise 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 (& or && operators) them, meaning if both  values are true, the result is true. If either value is false, the result is false. We can also OR ( I or II operators) the values, meaning if either value is true, the result is true.

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 = 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

Here is a quiz on comparsions.

 

Lesson navigation: