 Comparing Numbers in Java - dummies

The Java programming language has plenty of little squiggles and doodads for your various condition-forming needs. This section tells you all about them. This table shows you the operators that you can use to compare one thing with another.

Comparison Operators
Operator Symbol Meaning Example
== is equal to numberOfCows == 5
!= is not equal to buttonClicked != panicButton
< is less than numberOfCows < 5
> is greater than myInitial > ‘B’
<= is less than or equal to numberOfCows <= 5
>= is greater than or equal to myInitial >= ‘B’

You can use all Java’s comparison operators to compare numbers and characters. When you compare numbers, things go pretty much the way you think they should go. But when you compare characters, things are a little strange.

Comparing uppercase letters with one another is no problem. Because the letter B comes alphabetically before H, the condition ‘B’ < ‘H’ is true. Comparing lowercase letters with one another is also okay. What’s strange is that when you compare an uppercase letter with a lowercase letter, the uppercase letter is always smaller. So, even though ‘Z’ < ‘A’ is false, ‘Z’ < ‘a’ is true.

Under the hood, the letters A through Z are stored with numeric codes 65 through 90. The letters a through z are stored with codes 97 through 122. That’s why each uppercase letter is smaller than each lowercase letter.

Be careful when you compare two numbers for equality (with ==) or inequality (with !=). After doing some calculations and obtaining two double values or two float values, the values that you have are seldom dead-on equal to one another. (The problem comes from those pesky digits beyond the decimal point.)

For instance, the Fahrenheit equivalent of 21 degrees Celsius is 69.8, and when you calculate 9.0 / 5 * 21 + 32 by hand, you get 69.8. But the condition 9.0 / 5 * 21 + 32 == 69.8 turns out to be false. That’s because, when the computer calculates 9.0 / 5 * 21 + 32, it gets 69.80000000000001, not 69.8.