0
public class NullTernary {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        NullTernary obj= new NullTernary();
        obj.GetValue();
    }

    int GetValue()
     {
            return (true ? null : 0);
     }

}

Output of running main method of above class is,

Exception in thread "main" java.lang.NullPointerException
    at NullTernary.GetValue(NullTernary.java:13)
    at NullTernary.main(NullTernary.java:8)

is Java auto boxing the reason for NullPointerException ( i.e. when function tries to convert null value to Integer) or some other explanation?

If auto boxing to Integer theory is correct, I was wondering why auto boxing be done when expected value in int and not Integer ?

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
  • 2
    Actually it's auto-unboxing causing the NullPointerException. – Eran Jun 27 '16 at 09:53
  • saw [this one](http://stackoverflow.com/questions/3265948/nullpointerexception-with-autoboxing-in-ternary-expression) which explains it too. – Sabir Khan Jun 27 '16 at 09:55
  • `null` coul'd not be converted into `int` value. If you want to prevent the NPE, change signature from `int GetValue()` to `Integer GetValue()`. – Kartic Jun 27 '16 at 09:57

0 Answers0