Jaikant Bhagwan Das
Jaikant Bhagwan Das

Reputation: 227

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 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?

Upvotes: 7

Views: 297

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074475

Total Number of String objects created in the process?

Three: The one in the intern pool created via the literal and the two you create via new String.

One object will be eligible for GC.

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

  1. The one you created in this line:

    String str3=new String("JAVA");
    

    (since you later set str3 to null).

  2. The one you created temporarily in this line:

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

    That line creates a new String object, calls intern on it, and then saves a reference to the string from the pool. So in theory, it creates a String object that is immediately available for GC. (The JVM may be smart enough not to do that, but that's the theory.)

  3. Possibly, eventually, under the right conditions, even the string in the intern pool. Contrary to popular belief, strings in the intern pool are available for garbage collection as we can see from the answer to this other question. Just because they're in the permgen (unless you're using Oracle's JVM 7 or later) that doesn't mean they're not GC'd, since the permgen is GC'd too. So the question becomes: When or how is a string literal used in code no longer referenced? I don't know the answer, but I think a reasonable assumption would be: When and if the class using it is unloaded from memory. According to this other answer, that can only happen if both the class and its classloader are unloaded (and may not happen even then). If the class was loaded by the system classloader (the normal case), then presumably it's never unloaded.

So almost certainly just two (#1 and #2 above), but it was fun looking into #3 as well.

Upvotes: 12

Related Questions