String concatenation order of operations

Brian Goetz brian.goetz at
Wed Sep 8 00:55:39 UTC 2021

(Ouch.  Don't code like this.)

JLS 15.18.1 says:

> If only one operand expression is of type String, then string 
> conversion (§5.1.11)
> is performed on the other operand to produce a string at run time.

JLS 15.7.1 says "left to right", and also says "the left hand operand 
appears to be fully evaluated before any part of the right hand operand 
is evaluated."

Together, these say to me that string conversion on the left hand 
operand (if needed) must be performed _before_ evaluating the right hand 
operand.  Otherwise, in:

     notAString + aString

the left hand operand of the string concatenation is a string, which is 
the result of evaluating notAString and then string-converting it.  My 
read of 15.7.1 says that we should do that before evaluating any part of 

This suggests that the answer should be foofoobar, as the inline 
strategy does but not the indy strategy.

On 9/7/2021 8:40 PM, Liam Miller-Cushon wrote:
> I noticed that the result of string concatenation is different for the 
> invokedynamic and inline strategies when the arguments have side effects.
> With the inline strategy, each subexpression is evaluated and 
> converted to a string in order. With indy each subexpression is 
> evaluated in order *but not converted to a string*, and later each 
> subexpression is converted to a string in order.
> Is one of these behaviours more correct than the other?
> class T {
>   static String test() {
>     StringBuilder builder = new StringBuilder("foo");
>     return "" + builder + builder.append("bar");
>   }
>   public static void main(String[] args) {
>     System.err.println(test());
>   }
> }
> $ javac -XDstringConcat=inline ; java T
> foofoobar
> $ javac -XDstringConcat=indy ; java T
> foobarfoobar
> I read some of the related discussion about the spec requirements for 
> string concatenation in [1], and also some of the discussion around 
> JEP-280, and didn't find a conclusive answer. There was a bug [2] 
> about the evaluation order of string concat subexpressions with indy, 
> but that was about converting the arguments to strings in the wrong order.
> [1] 
> <>
> [2] 
> <>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the compiler-dev mailing list