Sunday, January 10, 2010

You can compare String objects in a variety of ways, and the results are often different. The correctness of your result depends largely on what type of comparison you need. Common comparison techniques include the following:

  • Compare with the == operator.
  • Compare with a String object’s equals method.
  • Compare with a String object’s compareTo method.
  • Compare with a Collator object.
  • Comparing with the == Operator
The == operator works on String object references. If two String variables point to the same object in memory, the comparison returns a true result. Otherwise, the comparison returns false, regardless whether the text has the same character values. The == operator does not compare actual char data. Without this clarification, you might be surprised that the following code snippet prints The strings are unequal.

String name1 = “Michèle”;
String name2 = new String(”Michèle”);
if (name1 == name2) {
System.out.println(”The strings are equal.”);
} else {
System.out.println(”The strings are unequal.”);
}

The Java platform creates an internal pool for string literals and constants. String literals and constants that have the exact same char values and length will exist exactly once in the pool. Comparisons of String literals and constants with the same char values will always be equal.

Comparing with the equals Method
The equals method compares the actual char content of two strings. This method returns true when two String objects hold char data with the same values. This code sample prints The strings are equal.

String name1 = “Michèle”;
String name2 = new String(”Michèle”);
if (name1.equals(name2) {
System.out.println(”The strings are equal.”);
} else {
System.out.println(”The strings are unequal.”);
}

Comparing with the compareTo Method
The compareTo method compares char values similarly to the equals method. Additionally, the method returns a negative integer if its own String object precedes the argument string. It returns zero if the strings are equal. It returns a positive integer if the object follows the argument string. The compareTo, method says that cat precedes hat. The most important information to understand about this comparison is that the method compares the char values literally. It determines that the value of ‘c’ in cat has a numeric value less than the ‘h’ in hat.
String w1 = “cat”;
String w2 = “hat”;
int comparison = w1.compareTo(w2);

No comments: