JLS string concatenation clarification

Alex Buckley alex.buckley at oracle.com
Wed Feb 12 10:49:48 PST 2014

+ is left-associative, so a+b+c means (a+b)+c. Neither a nor b nor c is 
a constant variable, so there are no constant expressions here. The 
evaluation of a+b should create a new String object, and the evaluation 
of its reference + c should create another.

s+=b means s=(String)(s+b), so one new String object should be created; 
similarly for s=(String)(s+c). The number of lines of source code is 

Are you writing JCK tests in this area?


On 2/12/2014 9:47 AM, Sergey Bylokhov wrote:
> Hi, Alex.
> Just to clarify " a new String is always created for a + ". How many
> String objects should be created in such code from specification point
> of view:
> String a,b,c; // locals variables
> 1) String s = a + b +c;  // One line
> or
> 2) String s=a; s+=b; s+=c; // One line
> On 2/12/14 8:28 AM, Alex Buckley wrote:
>> On 1/22/2014 2:14 PM, Alex Buckley wrote:
>>> On 1/21/2014 4:45 PM, Alex Buckley wrote:
>>>> - "Semi" constant expressions like s+"". Concatenating the empty string
>>>> literal "" with a String expression is mentioned in
>>>> https://bugs.openjdk.java.net/browse/JDK-4036535. The expectation (per
>>>> JLS1) that a new String object is always created in this case is
>>>> misplaced (per the JDK's actual behavior). But, the JLS never clarified
>>>> this.
>>> If compiler authors can confirm (on-list or privately) that indeed
>>> "concatenation with empty string does not create the new instance of
>>> String", then I will clarify the JLS.
>> On reflection, I wonder if the "sometimes" in JLS1 12.5 was written at
>> a point in history when the JDK didn't always create a new String for
>> +, at least when "" was an operand. After all, JDK-4036535 has
>> evidence that a JDK once arranged for ""+s1 == s1.
>> (An alternate theory is that "sometimes" refers to the creation of
>> some other String object, such as an intermediate result of string
>> conversion. But that's very subtle.)
>> Nowadays, javac and ecj both use a StringBuilder method chain,
>> culminating in a toString() call that ensures a new String object
>> every time. The "sometimes" is wrong and I have filed spec bug
>> JDK-8034259.
>> Alex
> --
> Best regards, Sergey.

More information about the compiler-dev mailing list