Strings - cont
Comparing Strings
To compare variables of the basic types for equality you use the = = operator (Two equals signs in a row). This does not apply to String objects (or any other objects). The expression,
string1 == string2
will check whether the two string variables refer to the same string. This expression will have the value of false if string1 and string2 reference separate strings, regardless of whether the strings happen to be the same.
Let’s demonstrate this with an example:
public class CompareStrings{
public static void main(String[] args){
String string1 = “The Java ”;
String string2 = “course”;
String string3 = “The Java ”;
if (string1 == string3){
// Now test for identity
System.out.println(“string1 and string3 point to the same string: ” + string1);
} else {
System.out.println(“string1 and string3 do not point to the same string”);
}
string3 = string1 + string2;
string1 += string2;
// Display the contents of the strings
System.out.println(“string3 is now: ” + string3);
System.out.println(“string1 is now: ” + string1);
if (string1 == string3){
// Now test for identity
System.out.println(“string1 and string3 point to the string: ” + string1);
} else {
System.out.println(“string1 and string3 do not point to the same string”);
}
}
}
You can use the method equals(), defined in the String class to check whether the strings that string1 and string3 reference are equal or not. If you want to compare two strings ignoring the case, you can use equalsIgnoreCase(). Both equals() and equalsIgnoreCase() return a boolean. To compare string1 to string2, you would do it as follows:
string1.equals(string2);
Exercise 3 – 2 Comparing strings with equals()
· change the CodeText above so you do the string comparison with the equals() method rather than the == operator.
No comments:
Post a Comment