• No results found

LEXICOGRAPHICAL ORDERING OF STRINGS

In document Java Programming Fundamentals (Page 154-159)

Recall that a string is a sequence of zero or more characters. If you look for the words like and lake in dictionary, the word lake appears before the word like. Th us, you could say that the word lake is smaller than the word like. Th us, there is an ordering of words in a diction-ary. Similarly, the word like is smaller than the word live and the word live is smaller than the word liver. Th is ordering is called lexicographical ordering.

In the lexicographical ordering, strings are compared character by character, from the beginning of the string. You have already seen that there is an ordering within the Unicode character set based on the collating sequence. If a mismatch occurs, as in the case of words like and lake, the character-by-character comparison stops and the order of the mismatched characters determines the order of words. Th us, in our example, the mismatch occurs at second character position. Now, the letter a is smaller than the letter i; therefore, the word lake is smaller than the word like. Similarly, considering words like and live, a mismatch occurs at third character. Again the letter k is smaller than the letter v; therefore, the word like is smaller than the word live. If no mismatch occurs, then eventually one or both strings may end. Th ese possibilities are explored next.

Consider the case in which character-by-character comparison continues and one of the strings ends. In our discussion, this will be the situation for words live and liver. You could treat this as a mismatch at fi ft h character position. Th e fi ft h character of the word live is a null character. Recall that null character is the fi rst character in the collating sequence.

Th us, any other character is larger than null character. In particular, character r is larger than null character. Th us, the string live is smaller than liver. Th us, in general, if two strings match until one of them ends, the string that ended is smaller than the other.

Th e only case that remains is both strings end simultaneously. In this case, both strings are identical or both strings are equal.

Apago PDF Enhancer

Th e class String has two methods to compare strings: equals and compareTo.

Th e syntax to use both methods is as follows:

strOne.equals(strTwo) strOne.compareTo(strTwo)

In the above syntax, strOne must be a String reference variable, whereas strTwo can be either a String reference variable or a String literal. Th e equals method returns a logical value. If both the strings are equal, then equals method returns true; oth-erwise returns false. Th e compareTo method returns an integer value. If strOne is smaller than strTwo, then the value returned is a negative integer. If strOne is larger than strTwo, then the value returned is a positive integer. If both strings are equal, the method compareTo returns integer 0. You should not relay on the actual integer returned by compareTo method. Rather, you should make your decisions on the basis of the sign of the number.

Example 4.7 Consider the following statements:

String strOne = "America the beautiful";

String strTwo = "America the beautiful!";

String strThree = "Maple leaf";

String strFour = "Maple Leaf";

String strFive = "Maple Leaf";

Table 4.8 illustrates the behavior of equals and compareTo methods.

Th e following program verifi es Table 4.8:

/**

Illustration of methods equals and compareTo in String class

*/

public class EqualsCompareToStringMethods {

public static void main(String[] args) {

String strOne = "America the beautiful";

String strTwo = "America the beautiful!";

String strThree = "Maple leaf";

String strFour = "Maple Leaf";

String strFive = "Maple Leaf";

System.out.println("strOne.equals(strTwo) is "

+ strOne.equals(strTwo));

System.out.println("strOne.compareTo(strTwo) is "

+ strOne.compareTo(strTwo));

Apago PDF Enhancer

System.out.println("strTwo.equals(strOne) is "

+ strTwo.equals(strOne));

System.out.println("strTwo.compareTo(strOne) is "

+ strTwo.compareTo(strOne));

System.out.println("strThree.equals(strFour) is "

+ strThree.equals(strFour));

System.out.println("strThree.compareTo(strFour) is "

+ strThree.compareTo(strFour));

System.out.println("strThree.equals((\"Maple leaf\") is "

+ strThree.equals(("Maple leaf"));

System.out.println("strFour.compareTo(strFive) is "

+ strFour.compareTo(strFive));

} }

Output strOne.equals(strTwo) is false strOne.compareTo(strTwo) is -1 strTwo.equals(strOne) is false strTwo.compareTo(strOne) is 1 strThree.equals(strFour) is false strThree.compareTo(strFour) is 32 strThree.equals("Maple leaf") is true strFour.compareTo(strFive) is 44

Self-Check

11. Assume the assignment statement strOne = "Bad";. What is strOne.

compareTo("Good")?

12. Assume the assignment statement strOne = "Better";. What is strOne.

compareTo("Best")?

TABLE 4.8 String Class Methods equals and compareTo

Method Invocation Value Retuned

strOne.equals(strTwo) false

strOne.compareTo(strTwo) An integer < 0

strTwo.equals(strOne) false

strTwo.compareTo(strOne) An integer > 0

strThree.equals(strFour) false

strThree.compareTo(strFour) An integer > 0 strThree.equals("Maple leaf") true

strFour.compareTo(strFive) An integer > 0

Apago PDF Enhancer

Advanced Topic 4.2: Equality Operators and String Class

Equality operators == and != can be applied to reference variables of String type. For example, if strOne and strTwo are two reference variables of the String type, both expressions

strOne == strTwo strOne != strTwo

are legal in Java. Th e expression strOne == strTwo returns true if the reference kept in both variables are identical. In other words, strOne== strTwo returns true if both refer to the same String object. Similarly, strOne == strTwo returns false if both refer to diff erent String objects.

In Java, String is a class. However, it is diff erent from other classes in many respects.

During compilation, a String literal is stored once only. Th erefore, the following two statements

String strOne = "Have a pleasant day!" //(1) String strTwo = "Have a pleasant day!" //(2)

create only one String object. To be more specifi c, as compiler encounters (1), the follow-ing steps are carried out:

a. Creates a reference variable strOne of String type

b. Creates a String object corresponding to the literal "Have a pleasant day!"

c. Assigns the reference of the object created in (b) to reference variable strOne As compiler encounters (2), the following steps are carried out:

a. Creates a reference variable strTwo of String type.

b. Recognizes the fact that a String object corresponding to the literal "Have a pleas ant day!" already exists. Th erefore, no new object is created.

c. Assigns the reference of the existing object to the reference variable strTwo.

Th erefore, the expression strOne == strTwo evaluates to true. However, if you input two identical String literals and then compare them using equality operator, the Java system will return a false value. In this case, system in fact creates two String objects. Th us, creating only one String object for a String literal is done during com-pilation and not during execution. Th ese ideas are illustrated in the following example:

/**

Illustration of equality operator in String class

*/

public class EqualityOperatorsOnString {

Apago PDF Enhancer

public static void main(String[] args) {

String strOne = "Have a nice day!";

String strTwo = "Have a nice day!";

String strThree = "Happy birthday to you";

String strFour = strThree;

String strFive = "America";

Scanner scannedInfo = new Scanner(System.in);

System.out.println("strOne == strTwo is "

+ (strOne == strTwo));

System.out.println("strThree == strFour is "

+ (strThree == strFour));

System.out.println("strOne == strThree is "

+ (strOne == strThree));

System.out.print("Input the word America twice : ");

strOne = scannedInfo.next();

strTwo = scannedInfo.next();

System.out.flush();

System.out.println("strOne is " + strOne);

System.out.println("strTwo is " + strTwo);

System.out.println("strOne == strTwo is "

+ (strOne == strTwo));

System.out.println("strOne.equals(strTwo) is "

+ strOne.equals(strFive));

System.out.println("strOne == strFive is "

+ (strOne == strFive));

System.out.println("strOne.equals(strFive) is "

+ strOne.equals(strFive));

} }

Output strOne == strTwo is true

strThree == strFour is true strOne == strThree is false

Input the word America twice : America America strOne is America

strTwo is America

strOne == strTwo is false strOne.equals(strTwo) is true

Apago PDF Enhancer

strOne == strFive is false strOne.equals(strFive) is true

Note that associated with each input of the word “America”, Java system created a new String object. As a consequence, strOne == strTwoisfalse. Further, even though there is a String object with string value “America”, during execution a new object is created. Th us, strOne == strFiveisfalse.

Note 4.3 String literals appearing in the code are processed during the compile time.

However, input values are processed at the execution time. As a consequence, storing a String literal once only rule applies during compile time and not at the execution time.

Self-Check

13. True or false: Let strOne and strTwo be two String references. If strOne == strTwo is true, then strOne.equal(strTwo) is also true.

14. True or false: If strOne.equal(strTwo) is false, then strOne ==

strTwo is false.

In document Java Programming Fundamentals (Page 154-159)