Java Challenge #1: String Pool

String pool challenge

Every time we create a different String, an object is created in the pool. How many objects were created in this situation?

Try to solve this challenge before seeing the answer below.

String_pool.jpg

Answer: 3 Strings and 1 StringBuilder are created in the concatenation. For performance reasons, the JVM creates a pool of Strings. When a String with the same value is created, the JVM does not create another object in the pool.

Why a StringBuilder is created in the concatenation?

For simple string concatenation, we don’t need to use StringBuilder. The Java compiler will do the that for us. But, if we need to concatenate inside a loop, it will be necessary to manually use StringBuilder otherwise the Java compiler won’t do that.

Written by
Rafael del Nero
Join the discussion

2 comments
    • Hi Shaun, thanks for the comment.

      For simple string concatenation, you don’t need to use StringBuilder. The Java compiler will do the that for you. But, if you need to concatenate inside a loop, you need to manually apply StringBuilder otherwise the Java compiler won’t do that for you.

Stand Out as a Java Developer and Get Your Dream Job!

You will get the book by email in a few minutes after registering.