Dads View

February 7, 2009

Java String Compare Headaches

Filed under: Java — Administrator @ 8:00 am

Every language has its quirks and Java is no different.
I just spent a couple hours discovering Java’s string comparison quirk.
To illustrate the issue, take the following Pop quiz:
With the following code what statement gets printed?
String a = “hello”;
String b = “there”;
String c = a + b;
if (c == “hellothere” ) {
System.out.println(“c is hellothere”);
}
else {
System.out.println(“c is not hellothere”);
}

If you answered: c is hellothere
You just stumbled over Java’s string comparison quirk.
The correct answer is: c is not hellothere

Boolean operators (like ==) should not be used to compare strings in Java.
The above comparison would result in “true” only if the two operands pointed to the exact same string in memory — not a likely scenario.
The following code produces the expected result:

String a = “hello”;
String b = “there”;
String c = a + b;
if (c.equals(“hellothere” )) {
System.out.println(“c is hellothere”);
}
else {
System.out.println(“c is not hellothere”);
}

What about greater than an less than comparisons?
You may have already guessed that the > (greater than) and < (less than)
operators don't work on Strings.
Instead use the String compareTo method.

String a = "hello";
String b = "there";

if (a.compareTo(b) < 0) {
System.out.println("a comes before b alphabetically");
}
else {
System.out.println("a comes after b alphabetically");
}

This code fragment will print "a comes before b alphabetically"

The call a.compareTo(b) will return the following values depending on strings a and b

A negative integer value if string a comes before string b when sorted alphabetically
A zero integer value if a and b are equal
A positive value of string a comes after string b when sorted alphabetically

For more information see:
Java String Practice Problems

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress