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.
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.
Why a StringBuilder? The end result of concatenation is another String.
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.