News for hackers. Stuff that matters.
Re:In Java 3 = 12 by rusk on Wednesday November 15, 2017 @03:32AM (#15702318)
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
Re:In Java 3 = 12 by rusk on Wednesday November 15, 2017 @05:02AM (#15702688)
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.htm...