Java Reference
In-Depth Information
The T parameter denotes a generic type. The return value of compareTo is an int , which
represents one of three outcomes:
Zero The two objects are equal.
Negative This object is less than the specifi ed object o .
Positive This object is greater than the specifi ed object o .
The ordering of objects that the compareTo method provides is referred to as the natural
ordering of the class. For example, the String class implements Comparable , and the
natural ordering of String objects is lexicographical, which is close to alphabetical except
uppercase letters always appear before lowercase letters. See if you can determine if the
following compareTo method calls return a positive number, a negative number, or 0:
4. String a = “hello”;
5. String b = “goodbye”;
6. String c= “Hello”;
7.
8. System.out.println(a.compareTo(b));
9. System.out.println(c.compareTo(b));
10. System.out.println(a.compareTo(c));
11. System.out.println(a.compareTo(a));
The output of the statements is
1
-31
32
0
The fi rst int displayed from line 8 is positive because the string “hello” is greater than
“goodbye“ . The actual value of the positive number is normally irrelevant, and for String
objects it represents the difference between the fi rst unequal characters between the two
strings. Line 9 compares “Hello” to “goodbye” and outputs -31 because H is uppercase and
appears before all lowercase letters. Therefore, “Hello” is less than “goodbye“ . Similarly,
“hello” is greater than “Hello” on line 10, which outputs 32 . Line 11 outputs 0 because
the two strings are equal.
The Difference Between == and equals
We discussed the differences between the == operator and the equals method of Object in
Chapter 1, “Fundamentals.” The == operator compares if two references point to the same
Search WWH ::




Custom Search