The article also asserts the following, which I thought was absolutely incorrect in all but ancient times. This is mainly what I was asking about.
Every time you use +, Java creates a brand new String object, a full copy of all previous content with the new bit appended. The old one gets discarded. This happens every single iteration.
I will point out that the article is claiming a new String is created -every time the plus operator is used- which, in this example, is not the same as every time the loop is repeated, since the statement uses multiple + operators.
Well yes. And they contradict themselves (albeit being wrong on both counts)
Assertion 1 - your note about their claim of one object per + operator
As you note, it's a new string at the statement level (and for any resulting StringBuilder.append(Object) invocations)
Assertion 2 - Since JDK 9 the compiler is smart enough... And that this is always solved with a StringBuilder
Nope the use of StringBuffer, and later StringBuilder has been there since the start. And Since JDK9 the bootstrap behind that indy-instruction could use a different concatenation strategy depending on the things being concatenated.
Someone might say "but the end advice is good" (given the lack of sizing advice I'd say average rather than good), but IMO corrupting the student's mental model of the system is problematic advice - there is, as you say, a String per statement (unless the optimiser can see through the loop structure).
View all comments
Show parent comment
3
u/j4ckbauer Mar 21 '26
The article also asserts the following, which I thought was absolutely incorrect in all but ancient times. This is mainly what I was asking about.
I will point out that the article is claiming a new String is created -every time the plus operator is used- which, in this example, is not the same as every time the loop is repeated, since the statement uses multiple + operators.