Remember that a variable is not an object; it points to an object. You can have more than one variable all pointing to the same object.
The expression 's + "hi"' creates a new String, and the variable "s" is set to point to it. The original String object that "s" pointed to is unchanged.
"java" doesn't get destroyed; it's just not referenced anymore. For most objects, that means the garbage collector will eventually delete it. For this particular String, since it's a literal (a String constant that appears in the source code) it's held in the string pool, so it won't be GCd.
String s4 is a new object...so calling == gives false as they are different objects...since s5 is "change me" + words....this creates a new string in the pool...so s1 and s5 refers to different objects in the string pool...s5 is not a constant because of this
Do What You Wanna Be....Taking Things The Way They Come
scjp 1.6 91 percent, scmad 90 percent(rounded off to nearest integer)
krishna anusha wrote: Then str1 and str2 are also different objects, but they are returning true. Why?
Because they are not different objects. The strings assigned to str1 and str2 are compile time constants, so the compiler uses the string pool, and hence, they refer to the same string object.