The total number of string objects created in the process?

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 the same object due to the concept of a string literal pool and str3 points to a new object because using the new operator and str4 points to the same points of the object on str1 and str2 because intern() checks the string pool for a string having the same meaning.

 str1=str2=str3=str4=null; 

One object will be eligible for GC. This is an object created using String str3=new String("JAVA") . The first String object is always accessible through a link stored in a string literal pool.

Is my explanation correct?

+7
source share
1 answer

The total number of string objects created in the process?

Three: one in the pool created through the literal, and two that you create with the new String .

One object will be eligible for GC.

I count two, and perhaps even all three under special circumstances:

  • The one you created on this line:

     String str3=new String("JAVA"); 

    (since you later set str3 to null ).

  • The one you created temporarily in this line:

     String str4=new String("JAVA").intern(); 

    This string creates a new String object, calls intern on it, and then stores the link to the string from the pool. Therefore, in theory, it creates a String object that is immediately available to the GC. (The JVM may be smart enough not to do this, but that's theory.)

  • Perhaps in the end, under the right conditions, even a row in the main pool. Contrary to popular belief, rows in the old pool are available for garbage collection, as we can see from the answer to this other question . Just because they are in permgen ( if you are not using Oracle JVM 7 or later ) does not mean that they are not GC'd , since the fit is also GC'd . So the question is: when or how is the string literal used in the code no longer referenced? I do not know the answer, but I think that a reasonable assumption would be: When and if the class using it is unloaded from memory. According to this other answer, this can happen only when both the class and its class loader are unloaded (and may not happen even then). If the class was loaded by the system class loader (normal case), then, apparently, it is never unloaded.

So there are almost certainly only two (# 1 and # 2 above), but it was fun to look at # 3.

+12
source

All Articles