This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I would like to add some more points to Ravikanth's post.
In the first line you are making a new String object str1 in the String pool and in the next line you are creating another object str2 using the same literal "java". So this time it won't create a new object, it will just assign the new object to existing object str1 object in the String pool.
This happens only when you say
I can't remember: isn't the String constant pool part of the head?
There are a few classes where the JVM has been optimised to reuse values. If you have a String literal like "pankaj" then every time the class loaders find that String literal they reuse the same object on the heap. This can be done because Strings are immutable. There is similar behaviour for a restricted set of values for Integer, and probably for a few other similar immutable classes. So two String references set equal to the same String literal will actually both point to the same object on the heap, unless you say (as somebody already mentioned) "new String("pankaj")".