How many objects are created after String concatenation using '+' operator?

Viewed 159

I want to ask that how many objects are created after execution of the following statement in java..

String str = "a"+"b"+"c"+"d"

In my opinion, only one object should get created and that of StringBuilder. Please correct me and explain the logic behind it..thanks in advance.

1 Answers

The simple answer is zero objects. That is a compile time constant expression, and the bytecode compiler evaluates it to "abcd" ... before creating the ".class" file.

Actually, with modern JVMs, the instantiation of String objects associated with literals and compile time constant expressions is lazy, so a single String object may be created the first time that statement is executed. But only the first time.

So a more correct answer is either zero or one String objects, depending on:

  • the JVM implementation of string literal interning (lazy or eager), and
  • whether this is the first execution of any statement that uses the "abcd" literal or compile time constant.

Then there is the possibility that the statement might be optimized away by the JIT compiler if str is never accessed.

And it gets even more complicated if you consider the possibility of class unloading.

Related