Java Reference
In-Depth Information
x
value
7
y
value 42
z
value
7
Then it includes a series of
println
statements that report the results of vari-
ous pairwise comparisons. In the first
println
statement, we compare
x
to
y
,
which involves comparing the
int
value
7
to the
int
value
42
. This pair has a
less-than relationship because
x
is less than
y
, so the method call returns a nega-
tive integer. In the second
println
statement, we compare
x
to
z
, which involves
comparing one occurrence of the
int
value
7
with another occurrence of the
int
value
7
. This second pair has an equality relationship because
x
equals
z
, so the
method call returns
0
. In the final
println
statement, we compare
y
to
x
, which
involves comparing the
int
value
42
to the
int
value
7
. This final pair has a
greater-than relationship because
y
is greater than
x
, so the method call returns a
positive integer.
Here is the actual output of the code:
-1
0
1
The values
-1
,
0
, and
1
are the standard values returned, but the
compareTo
method is not required to return these specific values. For example, consider a similar
piece of code that compares
String
values:
String x = "hello";
String y = "world";
String z = "hello";
System.out.println(x.compareTo(y));
System.out.println(x.compareTo(z));
System.out.println(y.compareTo(x));
The
compareTo
method of the
String
class compares strings alphabetically, so
there are similar relationships in this code:
x
is less than
y
because in an alphabetical
list
"hello"
comes before
"world"
,
x
is equal to
z
because the two occurrences of
"hello"
are equal, and
y
is greater than
x
because in an alphabetical list
"world"
comes after
"hello"
. But the output produced is slightly different from that pro-
duced by the
Integer
example:
Search WWH ::
Custom Search