0

This produces null pointer:

boolean treatNullAsFalse = false;
String what = null;
System.out.println(what == null ? (treatNullAsFalse ? false : null) :  what.equals("1")); // NULL POINTER

This doesn't.

boolean treatNullAsFalse = false;
String what = null;
System.out.println(what == null ? (treatNullAsFalse ? false : null) :  (Boolean)what.equals("1"));

Any help, why does the (Boolean) cast fix the issue? I thought ternary operators figure out return types at compile time, but here some unboxing is producing an NPE.

jn1kk
  • 5,012
  • 2
  • 45
  • 72
  • 1
    Unrelated: in my opinion, using nested ternaries makes for very hard to read code, and is best avoided. – forgivenson Apr 20 '15 at 14:48
  • 3
    If you apply the equals() method to a null String, it'll raise the exception. Try it outside the complicated ternary stuff and you'll be able to see it. – Alfabravo Apr 20 '15 at 14:49
  • 4
    @Alfabravo, it should never evaluate the right side expression if `what` is null. It knows the types at compile time. – jn1kk Apr 20 '15 at 14:51
  • What JVM/JDK version? – Necreaux Apr 20 '15 at 14:51
  • who down-vote this good question?!!!!! – Farvardin Apr 20 '15 at 15:04
  • This has nothing to do with ternaries but rather with `System.out.println` method. If you cast your `null` as a `String` or a char, your code will work: `System.out.println(what == null ? (treatNullAsFalse ? false : (String) null) : what.equals("1"));` – barti_ddu Apr 20 '15 at 15:09
  • Thanks mods for closing my question. To anyone who needs an actual answer, read this: second and third arguments need to be the same type. If one of the types is primitive, the other one has to be too. When it tries to unbox null (at runtime), it causes an NPE. Types are known at compile time, but not the ones that would avoid an NPE (boolean vs Boolean). – jn1kk Apr 20 '15 at 15:10
  • @barti_ddu it has nothing to do with System.out.println(). Try this: `Boolean b = (what == null ? (treatNullAsFalse ? false : null) : what.equals("1"))` – jn1kk Apr 20 '15 at 15:12
  • Good one, I assumed, that this was the same as with `System.out.println(null)`. – barti_ddu Apr 20 '15 at 15:34

0 Answers0