Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many Strings are created in memory?

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?

like image 578
committedandroider Avatar asked Jan 09 '23 20:01

committedandroider


2 Answers

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".

like image 194
rgettman Avatar answered Jan 16 '23 09:01

rgettman


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.

like image 39
Sotirios Delimanolis Avatar answered Jan 16 '23 07:01

Sotirios Delimanolis