0

If there are two strings string1 and string2 contained in string pool referenced to String literals, will System.out.println(string1 + string2) generate additional string object in String pool as string3=string1+string2;? If not, why?

Like to add for more clarity how many objects are allocated in pool in such case?

Prashant
  • 419
  • 6
  • 14
  • Possible duplicate of [this question](http://stackoverflow.com/questions/11989261/does-concatenating-strings-in-java-always-lead-to-new-strings-being-created-in-m) – Raul Rene Feb 28 '14 at 12:42

1 Answers1

2

The expression

"string1" + "string2"

will result in a string constant

"string1string2"

created at compile time and added to the enclosing class's constant pool.

The expression

string1 + string2

where string1 and string2 are arbitrary String-typed variables will compile into executable code which concatenates two strings. The result is not committed to the pool.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436