Ralph Morelli, Ralph Walde, Beryl Hoffman, David G. Cooper
Section7.9Comparing Strings
Comparing strings is another important task. For example, when a word processor performs a search and replace operation, it needs to identify strings in the text that match the target string.
Strings are compared according to their lexicographic order — that is, the order of their characters. For the letters of the alphabet, lexicographic order just means alphabetical order. Thus, a comes before b and d comes after c. The string “hello” comes before “jello” because h comes before j in the alphabet.
For Java and other programming languages, the definition of lexicographic order is extended to cover all the characters that make up the character set. We know, for example, that in Java’s Unicode character set the uppercase letters come before the lowercase letters (Table 5.13). So, the letter H comes before the letter h and the letter Z comes before the letter a.
Lexicographic order can be extended to include strings of characters. Thus, “Hello” precedes “hello” in lexicographic order because its first letter, H, precedes the first letter, h, in “hello.” Similarly, the string “Zero” comes before “aardvark,” because Z comes before a.
To determine lexicographic order for strings, we must perform a character-by-character comparison, starting at the first character and proceeding left to right. As an example, the following strings are arranged in lexicographic order:
For strings s1 and s2, s1 precedes s2 in lexicographic order if its first character precedes the first character of s2. If their first characters are equal, then s1 precedes s2 if its second character precedes the second character of s2; and so on. An empty string is handled as a special case, preceding all other strings.
publicbooleanprecedes(String s1,String s2){int minlen =Math.min(s1.length(), s2.length());// Pick shorter lengthfor(int k=0; k < minlen; k++)// For each char in shorter string{if(s1.charAt(k)!= s2.charAt(k))// If chars unequalreturn s1.charAt(k)< s2.charAt(k);// return true if s1's ch < s2's}// If all characters so far are equal// then s1 < s2 if it is shorter than s2return s1.length()< s2.length();}// precedes()
This method does a character-by-character comparison of the two strings, proceeding left to right, starting at the first character in both strings. Its for loop uses a counting bound, which starts at k equal to zero and counts up to the length of the shorter string. This is an important point in designing this algorithm. If you don’t stop iterating when you get past the last character in a string, your program will generate a StringIndexOutOfBounds exception. To prevent this error, we need to use the shorter length as the loop bound.
Note that the loop will terminate early if it finds that the respective characters from s1 and s2 are unequal. In that case, s1 precedes s2 if s1’s kth character precedes s2’s. If the loop terminates normally, that means that all the characters compared were equal. In that case, the shorter string precedes the longer. For example, if the two strings were “alpha” and “alphabet,” then the method would return true, because “alpha” is shorter than “alphabet.”
Using the precedes() method 7.9.2 as a guide, define and test a follows method. It should return true if and only if s1 follows s2 in lexicographic order.
The first comparison method, equals(), overrides the Object.equals() method. Two String s are equal if they have the exact same letters in the exact same order. Thus, for the following declarations,
You have to be careful when using Java’s equals() method. According to the default definition of equals(), defined in the Object class, “equals” means “identical.” Two objects are equal only if their names are references to the same object.
This is like the old story of the morning star and the evening star, which were thought to be different objects before it was discovered that both were just the planet Venus. After the discovery, it was clear that “the morning star” and “the evening star” and “Venus” were just three different references to one and the same object (Figure 7.9.3).
Given these three declarations, b1.equals(b2) and b1.equals(b3) would be false, but b2.equals(b3) would be true because b2 and b3 are just two names for the same object (Figure 7.9.4). So, in this case, “equals” really means “identical.”
Figure7.9.4.For most objects, equality means identity. JButtons b2 and b3 are identical (and, hence, equal), but JButtons b1 and b2 are not identical (and, hence, unequal).
Moreover, in Java, when it is used to compare two objects, the equality operator (==) is interpreted in the same way as the default Object.equals() method. So, it really means object identity. Thus, b1 == b2 would be false, because b1 and b2 are different objects, but b2 == b3 would be true because b2 and b3 refer to the same object.
These points are illustrated in the program shown in Listing 7.9.5. This program uses methods isEquals() and isIdentical() to perform the comparisons and print the results.
importjava.awt.*;publicclassTestEquals{staticButton b1 =newButton("a");staticButton b2 =newButton("b");staticButton b3 = b2;privatestaticvoidisEqual(Object o1,Object o2){if(o1.equals(o2))System.out.println(o1.toString()+" equals "+ o2.toString());elseSystem.out.println(o1.toString()+" does NOT equal "+
o2.toString());}// isEqual()privatestaticvoidisIdentical(Object o1,Object o2){if(o1 == o2)System.out.println(o1.toString()+" is identical to "+
o2.toString());elseSystem.out.println(o1.toString()+" is NOT identical to "+
o2.toString());}// isIdentical()publicstaticvoidmain(String argv[]){isEqual(b1, b2);// not equalisEqual(b1, b3);// not equalisEqual(b2, b3);// equalisIdentical(b1, b2);// not identicalisIdentical(b1, b3);// not identicalisIdentical(b2, b3);// identical}// main()}// TestEquals
Listing7.9.5.The TestEquals program tests Java’s default equals() method, which is defined in the Object class.
java.awt.Button[button0,0,0,0x0,invalid,label=a]
does NOT equal java.awt.Button[button1,0,0,0x0,invalid,label=b]
java.awt.Button[button0,0,0,0x0,invalid,label=a]
does NOT equal java.awt.Button[button1,0,0,0x0,invalid,label=b]
java.awt.Button[button1,0,0,0x0,invalid,label=b]
equals java.awt.Button[button1,0,0,0x0,invalid,label=b]
java.awt.Button[button0,0,0,0x0,invalid,label=a]
is NOT identical to java.awt.Button[button1,0,0,0x0,invalid,label=b]
java.awt.Button[button0,0,0,0x0,invalid,label=a]
is NOT identical to java.awt.Button[button1,0,0,0x0,invalid,label=b]
java.awt.Button[button1,0,0,0x0,invalid,label=b]
is identical to java.awt.Button[button1,0,0,0x0,invalid,label=b]
Subsection7.9.3String Identity Versus String Equality
In comparing Java String objects, we must be careful to distinguish between object identity and string equality. Thus, consider the following declarations:
Figure7.9.6.For String objects, equality and identity are different. Two distinct (nonidentical) String objects are equal if they store the same string value. So s1, s2, s4, s5, and s6 are equal. Strings s1 and s4 are identical, and so are strings s5 and s6.
The only true identities among these Strings are s1 and s4, and s5 and s6. In the case of s5 and s6, both are just references to the literal string, “hello”, as we described in Section 7.2.1. The program in Listing 7.9.7 illustrates these points.
importjava.awt.*;publicclassTestStringEquals{staticString s1 =newString("hello");// s1 and s2 are equal, staticString s2 =newString("hello");// not identicalstaticString s3 =newString("Hello");// s1 and s3 are not equalstaticString s4 = s1;// s1 and s4 are identicalstaticString s5 ="hello";// s1 and s5 are not identicalstaticString s6 ="hello";// s5 and s6 are identicalprivatestaticvoidtestEqual(String str1,String str2){if(str1.equals(str2))System.out.println(str1 +" equals "+ str2);elseSystem.out.println(str1 +" does not equal "+ str2);}// testEqual()privatestaticvoidtestIdentical(String str1,String str2){if(str1 == str2)System.out.println(str1 +" is identical to "+ str2);elseSystem.out.println(str1 +" is not identical to "+ str2);}// testIdentical()publicstaticvoidmain(String argv[]){testEqual(s1, s2);// equaltestEqual(s1, s3);// not equaltestEqual(s1, s4);// equaltestEqual(s1, s5);// equaltestEqual(s5, s6);// equaltestIdentical(s1, s2);// not identicaltestIdentical(s1, s3);// not identicaltestIdentical(s1, s4);// identicaltestIdentical(s1, s5);// not identicaltestIdentical(s5, s6);// identical}// main()}// TestStringEquals
------Program Output-----
hello equals hello
hello does not equal Hello
hello equals hello
hello equals hello
hello equals hello
hello is not identical to hello
hello is not identical to Hello
hello is identical to hello
hello is not identical to hello
hello is identical to hello
Listing7.9.7.Program illustrating the difference between string equality and identity.