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?
What you have here is a constant expression, as defined by the JLS, Section 15.28.
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
Literals of primitive type and literals of type String (§3.10.1, §3.10.2, §3.10.3, §3.10.4, §3.10.5)
Casts to primitive types and casts to type String (§15.16)
The unary operators +, -, ~, and ! (but not ++ or --) (§15.15.3, §15.15.4, §15.15.5, §15.15.6)
The multiplicative operators *, /, and % (§15.17)
The additive operators + and - (§15.18)
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With