Search code examples
javaconcatenationheap-memorystring-concatenationstring-pool

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?


Solution

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