Hello everyone, I'm a Java newbie, and this is my first post here.
I'm confused about Strings. I know that == checks whether two references lead to the same object, and .equals() checks for the String content itself. Therefore I don't understand why the following code produces true in the output. I've created two Strings, thus I have two different references to the different objects. The only possible clue for me is that somehow these two strings represent one object.
Thanks a lot for your help.
As you probably already know, you must always compare strings in Java using equals() and not using ==, because == indeed checks reference equality instead of comparing the content of the objects.
Java optimizes string literals. When you use the same string literal such as "ordinary string" multiple times in your code, then the Java compiler is smart enough to create only one String object and reuse that in all places where you're using the literal. This optimization is possible because class String is immutable (you can't change the content of a String object after it's created).
When writing it this way, it becomes quite obvious what is going on. And IMHO, this is the way you should use it. Imagine that you handle the ORDINARY_STRING "ordinary string" in 1023 places and your boss tells you to start using the ordinary string "ordinaryString"... Good luck actually finding and changing all occurrences.
I've looked at the String Pooling concept, it was quite easy, but I got one more question.
If the string is created somehow like this
it is referenced both from the String Pool and from the local variable myString.
But if the string is created using the keyword "new"
it is understood that it is referenced from myString2 but what about referencing from the Pool? Please check my question about this ambiguity in the article.
Joined: Oct 13, 2005
If you use the new operator you are telling the JVM you don’t want the String in the pool. It is rarely useful to use new String("..."), except when you have many Strings you want substrings from. Look for earlier discussions, for example, this thread.
Yes, thanks a lot. The article helped me, and the second thread too (the first one seemed a bit confusing). It seems that this topic itself is a special case. Even the neighbour post author says that
I suspect many programmers can go their whole careers without having a real need for this.
Therefore it's just useful to know about the Pool and don't forget not to use the "new" except creating substrings. All the rest seems to be from the "20" part of the "80/20" approach for me as a newbie now. Thanks for your help.