3 ms·
This code gives the same result: String splat = 1 + 2 + " = " + 1 + 2; System.out.println(splat); So the author's assertion that it is based o
by rusk 9y ago
This code gives the same result:
String splat = 1 + 2 + " = " + 1 + 2;
System.out.println(splat);
So the author's assertion that it is based on some `System.out.println` compiler magic is false.
The JLS spec [0] accounts for this in its treatment of the '+' operator:
"If the type of either operand of a + operator is String, then the operation is string concatenation."
This does seem like idiosyncratic behaviour for java to be honest.
I don't think it's the compiler doing it either, because this will throw a null-pointer exception:
Integer borken = null;
String splat = borken + 2 + " = " + 1 + 2;
System.out.println(splat);
EDIT: Also interesting, if I drop the language level to 1.4 I get this error:
Plus.java:8: error: bad operand types for binary operator '+'
String splat = borken + 2 + " = " + 1 + 2;
[0] https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.1 https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.htm...