The following snippet uses simple Java code.
package pkg;
final public class Main
{
final private class Demo
{
private Integer value = null;
public Integer getValue()
{
return value;
}
}
private Integer operations()
{
Demo demo = new Demo();
return demo==null?new Integer(1):demo.getValue();
}
public static void main(String[] args)
{
Main main=new Main();
System.out.println("Value = " + String.valueOf(main.operations()));
}
}
The above code works as expected with no problem and displays Value = null on the console.
In the following return statement,
return demo==null?new Integer(1):demo.getValue();
since the object demo of type Demo is not null, the expression after : which is demo.getValue() is executed which invokes getValue() within the inner Demo class which returns null and finally, it is converted to String and displayed on the console.
But when I modify the operations() method something like the one shown below,
private Integer operations()
{
Demo demo = new Demo();
return demo==null?1:demo.getValue();
}
it throws NullPointerException. How?
I mean when I use this return statement
return demo==null?new Integer(1):demo.getValue();
it works (doesn’t throw NullPointerException)
and when I use the following something similar return statement
return demo==null?1:demo.getValue();
it causes NullPointerException. Why?
This statement:
is actually being converted into something like this:
The type of the conditional expression is determined to be
int(notInteger) based on the rules laid out in the JLS, section 15.25, using binary numeric promotion (5.6.2). The conversion from the null reference tointthen triggers theNullPointerException.