View Single Post
  #7 (permalink)  
Old 12-31-2007, 05:46 AM
spoon! spoon! is offline
Member
 
Join Date: Dec 2007
Posts: 12
spoon! is on a distinguished road
Quote:
Originally Posted by CaptainMorgan View Post
Code:
String a = "Java String";
is a local variable and is placed on the stack frame of the current method. I think JavaBean makes a clarification in the latest post, but I just wanted clear this up.
No. There is no such thing in Java. All objects are on the heap.

The two things shown above are essentially the same. Except for a minor technicality with strings. String maintains an internal pool of strings. All string literals are automatically interned. (See String.intern()) So when you have a string literal in the code, it implicitly calls String.intern(). As a result, if you have a string literal that has the same content as another string literal that was evaluated earlier, it will evaluate to a String reference that references the same String object as the other one.

When you do "new String(...)", it creates a new String object that is not the same as any other object, so it is guaranteed not to be == to another object.

That is one reason you should not use == to compare strings.

You can manually intern strings with String.intern() if you really need to use == to compare strings.
Reply With Quote