enrii.blog

A passionate programmer’s findings in the world of internet.

Java: String Equality (Common Mistake)

March 15th, 2006

A very common mistake that lots of Java programmers will make is to use "==" to compare strings, rather than ".equals". That's what I keep reminding myself all the time and I never use "==" to do any string compare.

Just today, when I was testing a Java program, I noticed that the programmer used "==" to compare strings, everywhere in the 4000-line program. Why there's no logic error in the program? Why is the program still getting the correct output?

My first guess, in certain case, Java will return the correct result. But, when will Java give you correct result if you use "==" to do string compare?

Java Techniques explained:

Since Strings are objects, the equals(Object) method will return true if two Strings have the same objects. The == operator will only be true if two String references point to the same underlying String object. Hence two Strings representing the same content will be equal when tested by the equals(Object) method, but will only by equal when tested with the == operator if they are actually the same object.

So, I went through the program again and I realised that all the strings are predefined in the program. There is not even a single string is created during runtime (using "new String") and being compared to other strings.

However, to be safe, most of the time, programmers should use ".equals" rather than "==" to avoid unexpected outcome. It simply because ".equals" will compare 2 strings character by character to determine equality while "==" checks whether 2 string objects are identical. Try to do this experiment and you will understand:

String a = new String ("a");
String b = new String ("a");
System.out.println (a == b);

It returns false, while the following code returns true.

String a = new String ("a");
String b = new String ("a");
System.out.println (a.equals(b));

This is just a reminder to Java programmers, also to me.

If my article helped you solved your problem, consider buy me a beer!

Share this article: del.icio.us | digg it

Tags: ,

Related posts:

16 Responses


gbyeow says:

The ‘equals’ function compares object equality. When comparing Strings, I prefer a lexical comparison using the String.compareTo function.

However, that depends on the situation and performance has to be taken into consideration. Using equals runs faster than performing (String.compareTo(String) == 0) because of the extra cycles needed to make the == 0 comparison.

So yeah. Keep track of your clock cycles and use the function that best suits the situation.


Oliver Zheng says:

I’m not familiar with Java. So Java’s String type is a pointer?


EngLee says:

gbyeow,

I agree with you. A programmer should know what is best for his/her situation.

Oliver,

String is a class in Java. Java don’t have pointers as in C. But you can make your variables to work like pointer, but in a different way.

You might want to look in this article on pointers to understand how pointers work in Java, compared to C.


Kiki says:

Thank you for this interesting subject. It helps me a lot 🙂


EngLee says:

I’m glad that I helped somebody.


Ed says:

This article doesn’t correctly inform the reader of how Java uses Strings.

== looks at the address.
.equal does the internal object compare. The first thing in String equals is it looks to see if the ‘this’ reference matches and then returns true.

Java programs SHOULD NOT call a String via NEW but instead use quotes so the String value can be shared internally in a pool.

Kind regards


EngLee says:

Feel free to correct me. I’m no expert in Java string handling, I’m just writing based on my experience. When I encounter problem, I find solution and I blog about it.

The example given is simply to show how two strings that look the same would go wrong when comparing with “==”. Most of the time, a programmer would have done some string manipulations before they compare the strings. After some manipulations, whether you declare with new or not, you will go wrong with “==”.

Anyway, why do you need to declare 2 strings with the same value?


Static on WAQ177 » Java: String Equality (Common Mistake) - enrii.blog says:

[…] [From Java: String Equality (Common Mistake) – enrii.blog] […]


JavaLearner says:

Thank you ! I can now explain this to my daughter who is doing Java in high school.


destrukthorts says:

Thanks!, im doing a java version of a simple, solid, python process, thx a lot :-b


PROG [JAVA] - 9lives says:

[…] Gurdt das nie echt waar wa gij zegt he == vergelijk heel basisch de linker met de rechterkant Java: String Equality (Common Mistake) – enrii.blog dat dus. misschien gewoon slecht verwoord. __________________ Gamertag: […]


Bobby LeMain says:

I was messing around with this the other day. Apparently there was an update, because

String b = “b”;
if(b == “b”)
//returns true as a .NET programmer would expect


Umakant says:

hey dude thank you very much………….

i have just wasted my 4 hours to do this………

thanx


Seyfi says:

thanks a lot 😉


Thank you says:

Thank you, good post!


Rick O'Shay says:

The == operator generally works because the strings are pooled. String variables with the same contents usually end up “pointing” to the same object.

If you rely on this optimization, sooner or later you will get burned. Consider a servlet where the incoming strings from a request are not defined as string constants but rather dynamically allocated. You should compare strings using the “equals” method, not the == operator.