JLS string concatenation clarification
alex.buckley at oracle.com
Tue Feb 11 20:28:15 PST 2014
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
> 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.
More information about the compiler-dev