The String concatenation operator (+
) triggers the need for String conversion of the int
value because the first argument on the left is a String. Order of precedence causes the multiplication of the two ints to occur first in the second example before the concatenation operator is evaluated.
I'd need to check the bytecode but I believe the compiler uses a StringBuilder
here so the real code would look like:
System.out.println(new StringBuilder("Result").append(2).append(3).append(4));
System.out.println(new StringBuilder("Result").append(2).append(3 * 5));
Edit for completeness:
Your examples, because they are made up entirely of literals (String and primitive), are dealt with at compile time and simply turned into a string literal. This is a Compile Time Constant Expression. Precedence still applies so the result is the same.
If any of those were to have been a variable, for example:
int x = 5;
System.out.println("Result"+2+x);
then a StringBuilder
is used at runtime to concatenate the literal part with the variable's value.
(Edited to be authoritative after looking at the bytecode and JLS)