JLS string concatenation clarification

Sergey Bylokhov Sergey.Bylokhov at oracle.com
Wed Feb 12 09:47:25 PST 2014

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
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.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20140212/732a0c6c/attachment.html 

More information about the compiler-dev mailing list