String str1="JAVA";
String str2="JAVA";
String str3=new String("JAVA");
String str4=new String("JAVA").intern();
2 objects will be created. str1
and str2
refer to same object because of String literal pool concept and str3
points to new object because using new operator and str4
points to the same object points by str1
and str2
because intern()
method checks into string pool for string having same value.
str1=str2=str3=str4=null;
One object will be eligible for GC. That is the object created through String str3=new String("JAVA")
. The first String object is always accessible through reference stored in string literal pool.
Is my explanation correct?