Say I have this String
expression
String hi = "Tom" + "Brady" + "Goat"
I know that the String pool "allows a runtime to save memory by preserving immutable strings in a pool" String Pool
How many strings will be created in the string pool?
My initial guess was 5 - "Tom"
, "Brady"
, "Goat"
, "TomBrady"
,"TomBradyGoat"
, because of the order of operations of String
concatenation (left to right?) or is it only the final result, "TomBradyGoat", that is stored in the String pool?
As other people have mentioned, the compiler is good enough to optimize that very simple example, but if you have more complicated functionality (which is probably what you care about), it might not. For example:
This would result in 3 strings being created.
The other answers explain well why only 1 String is added to the String pool. But if you want to check and make some tests by yourself you can take a look on the bytecode to see the number of String created and added to the string pool. Ex:
Ex1:
ByteCode:
As you can see only 1 String is created
Ex2:
Bytecode:
As you can see 4 Strings are created
What you have here is a constant expression, as defined by the JLS, Section 15.28.
(other possibilities)
The compiler determines that the expression
"Tom" + "Brady" + "Goat"
is a constant expression, so it will evaluate the expression itself to"TomBradyGoat"
.The JVM will have only one string in the string pool,
"TomBradyGoat"
.At runtime, that piece of code will translate into a single
String
object. The compiler will take care of concatenation at compile time and add a single value in the constants pool.