Java代码片段中String对象创建数量疑问:6个还是11个?
Hey there! This is such a common point of confusion for Java certification exams—great catch for digging into the details. Let's break this down step by step to clear up why the book says 11 objects, and where your 6-object count is coming from.
First, a key rule to remember: When you concatenate strings with a variable (like your i here), Java doesn't just stitch strings directly. It implicitly creates a StringBuilder to handle the concatenation, then generates a new String from that builder. This is the hidden object creation you're missing!
1. Initial String: String hello = "hello";
This creates 1 String object in the string constant pool. No surprises here—this is the first object in our count.
2. Loop Iterations (5 total)
Each time you run hello = hello + i;, the compiler translates this to code that looks like this:
hello = new StringBuilder() .append(hello) .append(i) .toString();
That means 2 new objects are created per loop:
- 1
StringBuilderinstance (the helper for concatenation) - 1 new
Stringinstance (the result oftoString(), stored on the heap)
Multiply that by 5 loops, and you get 10 additional objects.
3. Total Object Count
Adding the initial String to the loop-created objects: 1 + 10 = 11 total objects. That's exactly what the book is referencing.
Your count makes total sense if you're only counting String objects: the initial "hello" plus 5 new Strings from each loop (1 + 5 = 6). But Java certification questions almost always count all objects created during execution—including the implicit StringBuilder instances that get created behind the scenes for variable-based concatenation.
One quick side note: If you were concatenating compile-time constants (like "hello" + "1"), the compiler would optimize this to a single String, no StringBuilder needed. But since i is a runtime variable, that optimization can't happen here.
内容的提问来源于stack exchange,提问作者chiperortiz

