In Java when we write
String S1 = "TestString";
String S2 = "TestString";
and then compare with if(S1==S2)
, we get true as the boolean result.
The explanation for the same being that the String constants are created in the String Pool and hence it is the same string constant that is being referred here by both S1 and S2.
Also, if we write something like
String S1 = new String("TestString");
String S2 = new String("TestString");
and then do the comparison with if(S1==S2)
, we get false.
The reason being that the references of S1 and S2 are different since the strings literals are created in the heap.
My Question is that where was the String literal "TestString" which was passed in the constructor created? Is it same as a String literal/constant? and hence should be created in the Pool as was in the case 1 ? if it is then when we write something like after the above two statements
String S3 = "TestString";
this should not create a new String literal and comparing if(S1==S3)
should give me true but it gives false.
So i am not able to figure out where and when is this string literal passed in the constructor getting created.
Any help would be greatly appreciated. Thanks