Java Reference
In-Depth Information
Notice that we slipped in a new symbol, > (greater than). The greater than symbol is an example of a comparison
operator. We spoke earlier about mathematical operations and their symbols, such as +, -, or *. Comparison
operations (also called logical operations) are also represented by symbols. Comparison operators are at the heart of a
condition. Many conditions are comprised of two fixed constants or variables (operands) separated by a comparison
operator. When a condition is encountered, the computer compares the values on either side of the comparison
symbol and returns a Boolean value of true or false . (This Boolean value can then be used as the basis for an if
statement.) The following table shows the various comparison symbols, an example using primitive values in a
condition, and the condition example results.
Symbol
Function
Example
Result
<
less than
1 < 2
true
>
greater than
1 > 2
false
>=
greater than or equal to
1 >= 2
false
<=
less than or equal to
1 <= 2
true
==
equal
1 == 2
false
!=
Not equal
1 != 2
true
Please note that the equal operator is represented by two equal signs! A common rookie mistake (that happens to
pros too!) is to use a single equal sign when trying to define a condition. A single equal sign is the assignment operator.
For instance, trying to assign 2 to 1 (1 = 2) makes no sense and not only does not result in a Boolean value of true or
false but will result in an error message.
Tutorial: Comparisons
Let's have a go at comparisons:
In the Tutorials project, copy the c5 package.
Paste the c5 package into Tutorials/src with the new name c6.
Create a new class in c6 called CondTestApp that has a main method stub.
Enter the following statement in the main method:
System.out.println(1=>2);
You should get an error (i.e., a red squiggly line beneath the >). Can you figure out what the problem is?
The “greater than or equal to” comparison must have the greater than symbol first and then the equal sign.
Yes, the JVM is that picky! The same is true for the “less than or equal” comparison.
Change the comparison to >=, save the source, and run CondTestApp as a Java application.
Notice the Boolean value that is displayed. Just like an addition operation, the computer performs the
comparison operation and returns the result. In this case, instead of adding two numbers and returning the sum,
the comparison operation is performed/evaluated and the Boolean result is returned. The result (in either the
addition or comparison case) is then displayed by the println method.
Comment out the println statement and add the following statement.
System.out.println(1=2);
 
 
Search WWH ::




Custom Search