0

The code below throws a NullPointerException but I don't understand why, the object is not null.

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

    public static void main(String[] args)  {
        A obj= new A();
        obj.GetValue();
    }
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
prabhakar Reddy G
  • 1,039
  • 3
  • 12
  • 23

1 Answers1

3

Because it is unboxing a null into int

(true ? null : 0); // returns null always

The return value is an int and converting a null into int throws an NPE

when your method returns a primitive you need to make sure that the value is never null. You can fix it by returning Integer

Integer GetValue() // allows nulls
{
    return (true ? null : 0);
}

But then again callers might fail

int x = GetValue(); //fails

returning an Optional would be a better fix.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77