Chapter 3: More Notes
Comparing Characters and Strings
if (ch1 > ch2) System.out.println (ch1 + " is greater than " + ch2); else System.out.println (ch1 + " is NOT greater than " + ch2);
In the Unicode character set all lowercase alphabetic characters (‘a’ through ‘z’ ) are in alphabetical order. The same is true of uppercase alphabetic characters ( ‘A’ through ‘Z’ ) and digits ( ‘0’ through ‘9’ ). The digits come before the uppercase alphabetic characters,
which come before the lowercase alphabetic characters.
Assuming that namel and name2 are String objects
if (namel.equals(name2)) System.out.println ("The names are the same."); else System.out.println ("The names are not the same.");
int result = namel.compareTo(name2); if (result < 0) System.out.println (namel + " comes before II + name2); else if (result == 0) System.out.println ("The names are equal."); else System.out.println (namel + " follows" + name2);
Keep in mind that comparing characters and strings is based on the Unicode character set. This is called a lexicographic ordering. If all alphabetic characters are in the same case (upper or lower), the lexicographic ordering will be alphabetic.
However, when comparing two strings, such as “able” and “Baker”, the compareTo method will conclude that “Baker” comes first because all of the uppercase letters come before all of the lowercase letters Unicode character set.
A string that is the prefix of another, longer string is considered to precede the longer string. For example, when comparing two strings such as “horse” and “horsefly”, the compareTo method will conclude that “horse” comes first.
comparing floating point values
if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal.");
The value of the constant TOLERANCE should be appropriate for the situation.
More Operators
Increment: i++ and ++i
Decrement: i- – and – -i
Programming Project 3.3
Change the solution to the Programming Project 3.2 so that the user can enter more than one year. Let the user end the program by entering a sentinel value. Validate each input value to make sure it is greater than or equal to 1582.