3

This little snippet causes NPE when data isn't foo nor bar.

Boolean baz = data == foo ? true : data == bar ? false : null

I'm guessing the compiler interprets the null as a null Boolean and tries to autounbox it, but why? Is it because there are true/false values present? If so, shouldn't they just be autoboxed instead? The variable is of type Boolean after all.

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
mak-g
  • 173
  • 2
  • 9
  • May i know what is type of foo, bar and data? – nagendra547 Sep 12 '17 at 14:16
  • 1
    The type of `data == foo ? true : data == bar ? false : null` is `boolean`. – Andy Turner Sep 12 '17 at 14:16
  • show declaration of foo and bar – Killer Death Sep 12 '17 at 14:17
  • same effect when you use braces around the second ternary? – chillworld Sep 12 '17 at 14:17
  • 2
    Use `Boolean.TRUE` instead of `true` (same for false). – Andy Turner Sep 12 '17 at 14:19
  • @AndyTurner It seems you're correct, because if I change `true` to `Boolean.TRUE` and `false` to `Boolean.FALSE` there is no NPE. But what determines the type of the ternary expression? First value returned? After all the `null` at the end has to be `Boolean` – mak-g Sep 12 '17 at 14:22
  • 2
    @mak-g https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25 - see Table 15.25-D particularly. – Andy Turner Sep 12 '17 at 14:22
  • @AndyTurner That explains all I wanted to know, thanks. – mak-g Sep 12 '17 at 14:30
  • @AndyTurner it's not of type `boolean`, it's of type `Boolean`; from your link: "A reference conditional expression is a poly expression if it appears in an assignment context or an invocation context ... The type of a poly reference conditional expression is the same as its target type". – daniu Sep 12 '17 at 14:35
  • @daniu it isn't reference conditional expression though, it's boolean conditional expression according to the link's defnition: " If both the second and the third operand expressions are boolean expressions, the conditional expression is a boolean conditional expression. For the purpose of classifying a conditional, the following expressions are boolean expressions: An expression of a standalone form (§15.2) that has type boolean or Boolean. (...) " – mak-g Sep 13 '17 at 14:40
  • @mak-g But "If both the second and the third operand expressions are boolean expressions" does not hold for `myBoolean ? true : null`: `null` is not a boolean expression. As an example, the context of this may be `boolean res1 = true; String res2 = null; System.out.println(myBoolean ? res1 : res2);` – daniu Sep 14 '17 at 06:49

0 Answers0