[java] String comparison vs. reference comparison

Started by
4 comments, last by GameDev.net 19 years, 6 months ago
I don't have any specific question, but I feel like this is one of those things waiting in the corner, ready to punch my in the face the moment i'm not paying attention. In terms of comparing strings, ==, Equals(), etc, what should I be aware of? Mainly, when will I get reference comparison and when will I get string comparison?
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
Advertisement
Hmm, I don't really understand what you're asking but here's what I know:

== compares references
Equals() compares String literals
If you want to be able to use == for equality checking, look into the String.intern() method. It (a) incurs an immediate speed penalty and (b) makes equality checking (with other strings that are known to be interned or final) into a pointer comparison.
Check out the API. As usual, it's pretty detailed on it. Basically, you should never use == to compare strings, sometimes to equal strings will return true even though you didn't make them reference to the same string object. Using String.equals() is usually best.
== will always compare object identity (reference comparison), as it does for any Object in Java.
.equals() and .compareTo() will always compare object value (value comparison; i.e. string comparison for Strings), assuming they are written appropriately (and you can rest assured they are for java.lang.String ;) ).

However, since String objects are immutable, it becomes possible to "intern" strings. A string which has been intern'd (short for internalized, I'd guess) behaves like any statically-known-at-compile-time String; which is to say, there will be only one String in memory with that given value. Subsequent attempts to make a new String with the same value will instead reference the old String, which is OK because it's immutable. (I'm not sure if this will fix references to existing Strings with the same value, or how that works, if so.)
Here is an interesting topic in a blog from someone working at sun:
http://blogs.sun.com/roller/comments/dreamwords/Weblog/can_i_use_to_compare

This topic is closed to new replies.

Advertisement