-3

To my understanding following code should not throw Null Pointer exception as I am safely using Optional interface.

However, when I ran this code it is throwing NPE.

public class Test {
        public static void main(String[] args) {
            final Integer inte = false ? 0 : Optional.ofNullable((Integer) null).orElse(null);
         }
    }

Please let me know if I am mistaken somewhere in my code and help me to rectify the same.

Curiosa Globunznik
  • 2,983
  • 1
  • 15
  • 23
Sachin Sachdeva
  • 10,744
  • 2
  • 45
  • 108

3 Answers3

8

The reason you get a NullPointerException, is that the type of the expression false ? 0 : Optional.ofNullable((Integer) null).orElse(null) is int (by JLS Table 15.25-C).

The expression Optional.ofNullable((Integer) null).orElse(null) evaluates to null, and casting a null to an int results in a NullPointerException.

Hoopje
  • 12,378
  • 7
  • 31
  • 48
1

Surely you'll get a NullPointerException, because your right hand side is just a very verboose way of saying null. You're wrapping a null in an Optional thus forcing the orElse which executes to null.

Having null in a statement that resolves to int, as explained by @Hoopje (even if it's assigned to an Integer variable) leads to a NullPointerException.

Just wrapping null in an Optional still gives you a null when unwrapping it again.

Nicktar
  • 5,433
  • 1
  • 26
  • 42
  • 3
    The author is assigning `null` to an `Integer` reference. I hope that clears the ask. – Agam Dec 04 '19 at 08:57
0

I found the work around

 final Integer inte = false ? (Integer)0 : Optional.<Integer>ofNullable(null).orElse(null);

or

final Integer inte = false ? (Integer)0 : Optional.ofNullable((Integer)null).orElse(null);

the type returned by the ternary operator is expected to be int (because of the literal 0).

Sachin Sachdeva
  • 10,744
  • 2
  • 45
  • 108
  • 2
    Actually, I did test this and it makes sense. Also, about ternary operator :"Ternary operator returns a value or expression included in the second or third part of it. It does not execute the statements." So in this case, the else part of the ternary operator was returning null, but the return type had been evaluated by the compiler to be int, instead of Integer. NPE was thrown because and int null was being returned, which is not possible. With the type casting of 0 to Integer, the returning value became Integer null, which is possible and that is what is happening. – Shivam Puri Dec 04 '19 at 08:56
  • 3
    Respect, Joker. Do you create riddles like this one on purpose? And re-post them [once a year](https://stackoverflow.com/questions/52147247/getting-unwanted-nullpointerexception-in-ternary-operator-why)? – Curiosa Globunznik Dec 04 '19 at 09:10