3 ms·
I had to look twice at this. I was surprised that I could add the string “=“ to ‘3’. I guess what’s happening here is the int gets boxed and then gets implicitl
by rusk 9y ago
I had to look twice at this. I was surprised that I could add the string “=“ to ‘3’. I guess what’s happening here is the int gets boxed and then gets implicitly converted to String. Proof of the pudding would be to try it with a simple string assignment rather than System.out.println. What happens after the “=“ is more straightforward
- rusk 9y agoThis 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...