When does the pool change?

Why does s1 and s2 point to the same object, whereas s1 and s3 doesn’t? (There is no usage of new keyword).

Because the concatenation happens at compile time, and the completed string therefore goes in the constant pool the same as in the first example. It’s a special case “known” to the compiler. It’s really meant so that long strings, concatenated this way over several lines, still get the benefit of the same performance improvements as simple string constants.

In the second example, you’re performing the calculation at runtime, so it won’t be part of the constant pool.

Note however that in the JLS the details of what can and can’t go in the string constant pool is deliberately left vague, so different implementations may optimise in different ways. It specifies certain rules as to what has to go in there, but don’t rely on this behaviour being consistent across implementations.

Leave a Comment