Java Reference
In-Depth Information
(
an integer value less than 0 if string str1
is less than string str2
0 if string str1 is equal to string str2
an integer value greater than 0 if string str1
is greater than string str2
str1.compareTo(str2) =
Consider the following statements:
String str1 = "Hello";
String str2 = "Hi";
String str3 = "Air";
String str4 = "Bill";
String str5 = "Bigger";
Using these variable declarations, Table 4-9 shows how the method compareTo works.
TABLE 4-9 Comparing Strings with the Method compareTo
Expression
Value
Explanation
str1 = "Hello" and str2 =
"Hi" . The first character of str1
and str2 are the same, but
the second character 'e' of str1
is less than the second character
'i' of str2 . Therefore,
str1.compareTo(str2) < 0 .
< 0
str1.compareTo(str2)
str1 = "Hello" . The first two
characters of str1 and "Hen" are
the same, but the third character 'l'
of str1 is less than the third
character 'n' of "Hen" . Therefore,
str1.compareTo("Hen") < 0 .
str1.compareTo("Hen")
< 0
str4 = "Bill" and str3 =
"Air" . The first character 'B' of
str4 is greater than the first
character 'A' of str3 . Therefore,
str4.compareTo(str3) > 0 .
> 0
str4.compareTo(str3)
str1 = "Hello" . The first character
'H' of str1 is less than the first
character 'h' of "hello"
because the Unicode value of 'H'
is 72, and the Unicode value
of 'h' is 104. Therefore,
str1.compareTo("hello") < 0 .
< 0
str1.compareTo("hello")
Search WWH ::




Custom Search