equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object being compared with the invoking String object. It returns
true if the strings contain the same characters in the same order, and false otherwise. The
comparison is case-sensitive.
To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When
it compares two strings, it considers A-Z to be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It, too, returns
true if the strings contain the same characters in the same order, and false otherwise.
Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " ->
"+
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " ->
"+
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " ->
"+
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " +
s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
The output from the program is shown here:
Hello
equals Hello -> true
Hello
equals Good-bye -> false
Hello
equals HELLO -> false
Hello
equalsIgnoreCase HELLO -> true
regionMatches( )
The regionMatches( ) method compares a specific region inside a string with another specific
region in another string. There is an overloaded form that allows you to ignore case in such
comparisons. Here are the general forms for these two methods:
boolean regionMatches(int startIndex, String str2,
int str2StartIndex, int numChars)
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home