if(x == z) System.out.println("x and z - same obj"); else System.out.println("x and z - different obj");
As, x and z are different objects allocated in memory, if you compare them with == operator, the compiler compares the two memory locations, and it may found different addresses. So, you are getting the out put of x and z -different objects.
I was trying to understand how String object gets created.
As mentioned in the K&B's book: "When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created."
Actually, Rakesh's code gives: "a and b - same obj", which makes sense to me. However, I am still wondering in my code why z is not refering the existing "abc" in the pool.
you seem to know a little bit more about the answer to your question than those who have replied!
The simple answer is that the '+' operator will always return a new String reference, unless you invoke the 'intern()' method:
Here, I take the new String reference returned by c + "c" and I force the JVM to look in the existing String pool, returning a reference to any match it finds. If you compare a and c now, they are equal, because the JVM did indeed find a match for the String "abc".
If it had found no match, then a new String would be added to the pool, and a reference to that would have been returned