what happens with new String(“”) in String Constant pool

前端 未结 5 1876
南方客
南方客 2021-01-24 07:05

if i create a string object as

String s=new String(\"Stackoverflow\");

will String object created only in heap, or it also makes a copy in Str

5条回答
  •  借酒劲吻你
    2021-01-24 08:05

    The new String is created in the heap, and NOT in the string pool.

    If you want a newly create String to be in the string pool you need to intern() it; i.e.

    String s = new String("Stackoverflow").intern();
    

    ... except of course that will return the string literal object that you started with!!

    String s1 = "Stackoverflow";
    String s2 = new String(s1);
    String s3 = s2.intern();
    
    System.out.println("s1 == s2 is " + (s1 == s2));
    System.out.println("s2 == s3 is " + (s2 == s3));
    System.out.println("s1 == s3 is " + (s1 == s3));
    

    should print

    s1 == s2 is false
    s2 == s3 is false
    s1 == s3 is true
    

    And to be pedantic, the String in s is not the String that was created by the new String("StackOverflow") expression. What intern() does is to lookup the its target object in the string pool. If there is already a String in the pool that is equal(Object) to the object being looked up, that is what is returned as the result. In this case, we can guarantee that there will already be an object in the string pool; i.e. the String object that represents the value of the literal.

提交回复
热议问题