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

前端 未结 5 1860
南方客
南方客 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 07:55

    You only get a string into the constant pool if you call intern or use a string literal, as far as I'm aware.

    Any time you call new String(...) you just get a regular new String object, regardless of which constructor overload you call.

    In your case you're also ensuring that there is a string with contents "Stackoverflow" in the constant pool, by the fact that you're using the string literal at all - but that won't add another one if it's already there. So to split it up:

    String x = "Stackoverflow"; // May or may not introduce a new string to the pool
    String y = new String(x);   // Just creates a regular object
    

    Additionally, the result of a call to new String(...) will always be a different reference to all previous references - unlike the use of a string literal. For example:

    String a = "Stackoverflow";
    String b = "Stackoverflow";
    
    String x = new String(a);
    String y = new String(a);
    
    System.out.println(a == b); // true due to constant pooling
    System.out.println(x == y); // false; different objects
    

    Finally, the exact timing of when a string is added to the constant pool has never been clear to me, nor has it mattered to me. I would guess it might be on class load (all the string constants used by that class, loaded immediately) but it could potentially be on a per-method basis. It's possible to find out for one particular implementation using intern(), but it's never been terribly important to me :)

提交回复
热议问题