1

This is similar to java ternary conditions strange null pointer exception and java: weird NullPointerException in ternary operator (? : ) but not exactly the same question.

Consider this example with a Box and a Thing. Why is NullPointerException thrown, why is not autoboxing working on the primitive integer 1?

public class Box {

    public Integer getHeight() {
        return null;
    }
}
public class Thing {

    private Box box;

    public void doThings() {
        setBox(new Box());

        try {
            System.out.println(getBox() != null ? getBox().getHeight() : Integer.valueOf(1)); // works
            System.out.println(getBox() != null ? null : 1); // works
            System.out.println(getBox() != null ? getBox().getHeight() : 1); // throws NPE
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    public Box getBox() {
        return box;
    }

    public void setBox(Box box) {
        this.box = box;
    }
}
rikardh
  • 21
  • 1
  • 1
    Does this answer your question? [Booleans, conditional operators and autoboxing](https://stackoverflow.com/questions/3882095/booleans-conditional-operators-and-autoboxing) or [NullPointerException with autoboxing in ternary expression](https://stackoverflow.com/questions/3265948/nullpointerexception-with-autoboxing-in-ternary-expression) or [Strange Java behaviour. Ternary operator](https://stackoverflow.com/questions/17934526/strange-java-behaviour-ternary-operator) – Ivar Sep 29 '21 at 08:58
  • 2
    1st case: you explicitly have two `Integer`s, no auto-anything happens, 2nd case: the compiler sees the `null` and knows you do not want an `int` -> the 1 is auto boxed. 3rd case: the compiler sees a 1 and an Integer and tries to auto-unbox -> boom. – luk2302 Sep 29 '21 at 08:59
  • 2
    One of my favorite bits of weirdness with the ?: operator is `Number n = (true) ? Integer.valueOf(0) : Double.valueOf(0); System.out.println(n instanceof Double);` prints true. http://errorprone.info/bugpattern/ConditionalExpressionNumericPromotion – Andy Turner Sep 29 '21 at 09:04
  • @luk2302 about the 3rd case, why does the compiler see a 1 and an Integer? Does it not se a null and a 1? – rikardh Sep 29 '21 at 09:09
  • No, the compiler does not call the method, the compiler only sees `getHeight` having an `Integer` return type, it does not know about any values it may or may not have. – luk2302 Sep 29 '21 at 09:10
  • @luk2302 ok, then this answers my question. Compiler sees an Integer and an int and then chooses to try to auto-unbox null to int. Thanks – rikardh Sep 29 '21 at 09:14

0 Answers0