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

java, string

Solution

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()

Problem

How many Java string objects will be created in the following statement? ``` String s = "abc" + "xyz"; ``` I guess three?

Original source

Related problems