we make the following String objects?
String str1 = new String("ABC");
String str2 = new String("ABC");
String str3 = "ABC";
String str4 = "ABC";
Two questions on above :
-
system.out.println("valof str1 "+str1 );— it printsstr1as ABC
But when we compareif(str1==str2), it compares the refrences of string object. How does
jvm get to differnce? -
str1has differnt reference fromstr2andstr3butstr3andstr4have same references so does jvm check if the string we are going to create with equal operator(instead of new) already exists (if it exist it does not create new object just assign the same refernce to new variable i.estr4) but it does not do this verfication in case of new operator?
In Java, string literals (bare
"ABC"instead ofnew String("ABC")) are interned. That is, there is only one copy stored in the JVM, and that is always the copy that’s used. That’s why they compare equal when using==.The following comparisons are also always true: