How many objects are created at each line and finally at line 7?
Actually as we know when objects created like in 3 or 4 in those cases only one object is created and they are stored in string pool no object created in heap.
so at line 3 one object should be created.
next at line 4 no object should be created as they are all ready in the pool, it will simply reference that.
at line three as it is created by new operator one is created in the heap and as its one reference is available in pool it don't create the second object..so only one object created.
finally at last totally three object will be created..
but i am not sure about it as these are my hypothetical answer....
Your hypothesis for 1~3 sounds good to me. You could check if line 3 and 4 are pointing at the same object by checking their hash code (and they are the same if you do check). So where does your 3rd created object come from? :)
The default .hashCode() method uses the contents of the string to create the hashcode so unsuprisingly all the values are the same. A better test is:
String str3 = new String("ABC");
if( str1 == str2 )
System.out.println( "str1 and str2 reference same object");
System.out.println( "str1 and str2 do not reference the same object");
if( str1 == str3 )
System.out.println( "str1 and str3 reference same object");
System.out.println( "str1 and str3 do not reference the same object");
if( str2 == str3 )
System.out.println( "str2 and str3 reference same object");
System.out.println( "str2 and str3 do not reference the same object");
thanks i got it i was using overridden method of hashcode by String class but Object class hashcode use memory address for calculating hashcode so can i call the Object class hashcode method from the String class reference?
i tried with ((Object)str1).hashcode() but due to polymorphism it again calls String class overridden method only.