1

Here is my code:

String s = new String("1"); // here I know that "1" is created in const pool    
String s2 = new String("1") + new String("1"); 

Does "11" created in the String pool immediately in this code? If not, should I invoke s2.intern() to put "11" to String pool?

--------------udapte 22/9/2016---------------------

Here I have somethings confuse me: Both new Stirng("1") and new String("1") + new String("1") invoke the same native method System.arraycopy which I learn from JDK6.

Now why does "1" will be created in String pool but "11" does't? Does anything make differences in StringBuilder? Maybe method "append" or ...?

I will be appreciated for your assistance.

GanGan
  • 39
  • 5

2 Answers2

1

But does "11" created in const pool immediately in this code?

No. It will not be created in the String constants pool. StringBuilder will be used to join the two "1"s together to form "11" which will be on the heap.

Should I invoke s2.intern() to put 11 to const pool?

Yes. You should explicitly invoke intern if you want to to put 11 (got by adding 2 "1"s (and not the literal "11") in the String constants pool.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

String s will not be created in the common pool. The new operator will cause the JVM to allocate memory for the new string literal "1" in heap memory.

String s1 = "1"; // Common pool
String s2 = new String("1"); // heap allocated memory

In your example:

String s2 = new String("1") + new String("1");

As for your question : https://www.ntu.edu.sg/home/ehchua/programming/java/J3d_String.html

The result of concatenating two strings will be allocated on heap memory.

user207421
  • 305,947
  • 44
  • 307
  • 483