String concatenation order of operations

Brian Goetz brian.goetz at oracle.com
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 
aString.

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 T.java ; java T
> foofoobar
>
> $ javac -XDstringConcat=indy T.java ; 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] 
> http://mail.openjdk.java.net/pipermail/compiler-dev/2015-March/009357.html 
> <http://mail.openjdk.java.net/pipermail/compiler-dev/2015-March/009357.html>
> [2] https://bugs.openjdk.java.net/browse/JDK-8200118 
> <https://bugs.openjdk.java.net/browse/JDK-8200118>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20210907/bee0d0b2/attachment-0001.htm>


More information about the compiler-dev mailing list