How many Java string objects created in the code String s="abc"+"xyz";?

How many Java string objects will be created in the following statement?

String s = "abc" + "xyz"; 

I guess three?


Solution 1:

The compiler creates 1 String per JVM start, because the compiler can determine the resulting String at compile time, it is interned and statically stored in the JVM's String Table.


FYI, if the statement were concatenating variables (not determinable at runtime), 1 String would be created, but it would create a StringBuilder too. The code would compile to:

new StringBuilder().append(abcVar).append(xyzVar).toString()

Solution 2:

The answer is one global String object per program run, and zero new String objects per statement execution. This is because the Java Language Specification says the expression "abc" + "xyz" is a compile-time constant [0], and that no new String object will be created when the statement is executed [1].

References

[0]: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313

Examples of constant expressions:

"The integer " + Long.MAX_VALUE + " is mighty big."

[1]: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1

If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28)) that is the concatenation of the