Java Reference
In-Depth Information
45
46
// test regionMatches (case sensitive)
47
if (
s3.regionMatches( 0 , s4, 0 , 5 )
)
48
System.out.println( "First 5 characters of s3 and s4 match" );
49
else
50
System.out.println(
51
"First 5 characters of s3 and s4 do not match" );
52
53
// test regionMatches (ignore case)
54
if (
s3.regionMatches( true , 0 , s4, 0 , 5 )
)
55
System.out.println(
56
"First 5 characters of s3 and s4 match with case ignored" );
57
else
58
System.out.println(
59
"First 5 characters of s3 and s4 do not match" );
60
}
61
} // end class StringCompare
s1 = hello
s2 = goodbye
s3 = Happy Birthday
s4 = happy birthday
s1 equals "hello"
s1 is not the same object as "hello"
Happy Birthday equals happy birthday with case ignored
s1.compareTo(s2) is 1
s2.compareTo(s1) is -1
s1.compareTo(s1) is 0
s3.compareTo(s4) is -32
s4.compareTo(s3) is 32
First 5 characters of s3 and s4 do not match
First 5 characters of s3 and s4 match with case ignored
Fig. 14.3 | String methods equals , equalsIgnoreCase , compareTo and regionMatches .
(Part 2 of 2.)
String Method equals
The condition at line 17 uses method equals to compare String s1 and the String literal
"hello" for equality. Method equals (a method of class Object overridden in String )
tests any two objects for equality—the strings contained in the two objects are identical .
The method returns true if the contents of the objects are equal, and false otherwise.
The preceding condition is true because String s1 was initialized with the string literal
"hello" . Method equals uses a lexicographical comparison —it compares the integer
Unicode values (see online Appendix H for more information) that represent each charac-
ter in each String . Thus, if the String "hello" is compared to the string "HELLO" , the
result is false , because the integer representation of a lowercase letter is different from that
of the corresponding uppercase letter.
 
Search WWH ::




Custom Search