Sign in to follow this  
Promit

[java] String comparison vs. reference comparison

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
== 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.)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this