Number of objects created when using String intern method in Java

前端 未结 3 998
我在风中等你
我在风中等你 2021-01-27 09:38

I understand String\'s intern method.

String s1 = \"Hello\";             
String s4 = new String(\"Hello\").intern();  

Output of (s1 ==

3条回答
  •  礼貌的吻别
    2021-01-27 09:58

    ...how many objects will be created?? One or two?

    Two. But only one of them is kept. The other is immediately eligible for garbage collection.

    Will new operator creates one more object?

    Yes. Briefly. But then you call its .intern method and save the result. Its .intern method will return the same interned string that s1 points to, and so the object created via new is (again) immediately eligible for GC.

    We can see this if we look at the bytecode:

      public static void main(java.lang.String[]);
        Code:
           0: ldc           #2                  // String Hello
           2: astore_1
           3: new           #3                  // class java/lang/String
           6: dup           
           7: ldc           #2                  // String Hello
           9: invokespecial #4                  // Method java/lang/String."":(Ljava/lang/String;)V
          12: invokevirtual #5                  // Method java/lang/String.intern:()Ljava/lang/String;
          15: astore_2      
          16: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
          19: aload_2       
          20: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
          23: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
          26: aload_1       
          27: aload_2       
          28: if_acmpne     35
          31: iconst_1      
          32: goto          36
          35: iconst_0      
          36: invokevirtual #8                  // Method java/io/PrintStream.println:(Z)V
          39: return        
    

    3-9 create a new String object from "Hello", leaving its reference on the stack, and then we immediately call intern (which pops the reference to the new string from the stack), and store the return value of intern in s4. So the object temporarily created is no longer referenced.

提交回复
热议问题