Java Reference
In-Depth Information
-15
0
15
Instead of -1 and 1 , we get -15 and 15 . You don't really need to know where these
numbers come from—the only important fact is whether they are negative or positive—
but for those of you who are curious, the -15 and 15 represent the distance between
the positions of the characters ' h ' and ' w ' in type char . ' w ' appears 15 positions
later than ' h ' .
So while the values -1 and 1 are often returned by a comparison function, that
won't always be the case. The important thing to remember is that “less-than” rela-
tionships are indicated by a negative number and “greater-than” relationships are
indicated by a positive number.
Also keep in mind that the relationship operators that we've been using since
Chapter 4 have a different syntax. For example, you've seen that if two variables x
and y are of type int or double , you can compare them by using operators like
< and > :
int x = 7;
int y = 42;
if (x < y) {
System.out.println("x less than y");
}
Even though the String class implements the Comparable interface, you can't
use the relational operators to compare String s. The following code will not
compile:
// illegal--can't compare objects this way
String s1 = "hello";
String s2 = "world";
if (s1 < s2) {
System.out.println("s1 less than s2");
}
Instead, call the compareTo method, as in:
String s1 = "hello";
String s2 = "world";
if (s1.compareTo(s2) < 0) {
System.out.println("s1 less than s2");
}
 
Search WWH ::




Custom Search