JLS string concatenation clarification

Alex Buckley alex.buckley at oracle.com
Tue Jan 21 16:45:52 PST 2014


No, we can't. There are three levels to consider:

- "Real" constant expressions like 3+"". They can avoid creating a new 
String object per https://bugs.openjdk.java.net/browse/JDK-4836025.

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

- "Not" constant expressions: s+empty. Not detectable in general. Always 
creates a new String object.

Alex

On 1/21/2014 10:41 AM, Martin Buchholz wrote:
> Can we agree that when
> String empty = "";
> then
> s + empty
> should be permitted to be the same object as s.
>
>
> On Tue, Jan 21, 2014 at 9:59 AM, Louis Wasserman <lowasser at google.com
> <mailto:lowasser at google.com>> wrote:
>
>     JLS 15.18.1 states:
>
>         The |String| object is newly created (§12.5
>         <http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.5>)
>         unless the expression is a compile-time constant expression
>         (§15.28
>         <http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28>).
>
>     JLS 12.5 states:
>
>         Execution of a string concatenation operator (§15.18.1
>         <http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.1>)
>         that is not part of a constant expression (§15.28
>         <http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28>)
>         sometimes creates a new |String| object to represent the result.
>
>
>     It's not clear to me, from reading this, whether string
>     concatenation with + /always/ creates a new String object or
>     /sometimes /creates a new String object.  15.18.1 seems to imply
>     always, but 12.5 says "sometimes."
>
>     My understanding is that String.concat used to be used for string
>     concatenation, and String.concat currently returns its receiver if
>     its argument is the empty string.  This seems to be evidence for the
>     "sometimes" interpretation.
>
>     --
>     Louis Wasserman
>
>


More information about the compiler-dev mailing list