Comparing Strings

Characters are compared based on their Unicode values.

Click here to view code image

boolean test = ‘a’ < ‘b’;    // true since 0x61 < 0x62

Two strings are compared lexicographically, as in a dictionary or telephone directory, by successively comparing their corresponding characters at each position in the two strings, starting with the characters in the first position. The string “abba” is less than “aha”, since the second character ‘b’ in the string “abba” is less than the second character ‘h’ in the string “aha”. The characters in the first position in each of these strings are equal.

The following public methods can be used for comparing strings:

Click here to view code image

boolean equals(Object obj)
boolean equalsIgnoreCase(String str2)

The String class overrides the equals() method from the Object class. The String class equals() method implements String object value equality as two String objects having the same sequence of characters. The equalsIgnoreCase() method does the same, but ignores the case of the characters.

int compareTo(String str2)

The String class implements the Comparable<String> interface (§14.4, p. 761). The compareTo() method compares the two strings, and returns a value based on the outcome of the comparison:

  • The value 0, if this string is equal to the string argument
  • A value less than 0, if this string is lexicographically less than the string argument
  • A value greater than 0, if this string is lexicographically greater than the string argument

Here are some examples of string comparisons:

Click here to view code image

String strA = new String(“The Case was thrown out of Court”);
String strB = new String(“the case was thrown out of court”);
boolean b1 = strA.equals(strB);             // false
boolean b2 = strA.equalsIgnoreCase(strB);   // true
String str1 = “abba”;
String str2 = “aha”;
int compVal1 = str1.compareTo(str2);         // negative value => str1 < str2


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *