JLS string concatenation clarification

Sergey Bylokhov Sergey.Bylokhov at oracle.com
Thu Feb 13 01:52:32 PST 2014


On 12.02.2014 22:49, Alex Buckley wrote:
> + 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.
So how we follow the specification here if it is compiled to:
s =  a + b + c ==>> s = 
StringBuilder().append(s).append(a).append(b).append(c).toString();
>
> 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 irrelevant.
>
> Are you writing JCK tests in this area?
no, I try to understand this area
>
> Alex
>
> 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.
>>


-- 
Best regards, Sergey.



More information about the compiler-dev mailing list