Java Reference
In-Depth Information
TABLE 4-9 Comparing Strings with the Method compareTo (continued)
Expression
Value
Explanation
str2 = "Hi" . The strings str2 and
"Hi" are of the same length
and their corresponding
characters are the same. Therefore,
str2.compareTo("Hi") = 0 .
= 0
str2.compareTo("Hi")
4
str4 = "Bill" has four characters
and "Billy" has five characters.
Therefore, str4 is the shorter string.
All four characters of str4
are the same as the corresponding
first four characters of
"Billy" , and "Billy" is the
larger string. Therefore,
str4.compareTo("Billy") < 0 .
< 0
str4.compareTo("Billy")
str5 = "Bigger" has six
characters and "Big" has three
characters. Therefore, str5 is the
larger string. The first three characters
of str5 are the same as the
corresponding first three
characters of "Big" . Therefore,
str5.compareTo("Big") > 0 .
str5.compareTo("Big")
> 0
str1 = "Hello" has five characters
and "Hello " has six characters.
Therefore, str1 is the shorter string.
All five characters of str1 are
the same as the corresponding
first five characters of "Hello " ,
and "Hello " is the larger
string. Therefore,
str1.compareTo("Hello ") < 0 .
< 0
str1.compareTo("Hello ")
The program in Example 4-23 evaluates the expressions in Table 4-9.
EXAMPLE 4-23
//The String method compareTo
public class StringComparison
{
public static void main(String[] args)
Search WWH ::




Custom Search