Unknown NullPointerException in Java

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 without problems and displays Value = nullon the console.

In the following expression return

return demo==null?new Integer(1):demo.getValue();

since the object demois demo not of type null, an expression is executed after :, which demo.getValue(), which calls getValue()inside the internal demo, which returns nulland, finally, is converted to String and displayed on the console.

But when I change the method operations()as shown below,

private Integer operations()
{
    Demo demo = new Demo();    
    return demo==null?1:demo.getValue();
}

he throws out NullPointerException. How?


I mean when I use this operator return

return demo==null?new Integer(1):demo.getValue();

he works (doesn't quit NullPointerException)

and when I use the following something like return statement

return demo==null?1:demo.getValue();

NullPointerException. ?

+5
2

:

return demo==null?1:demo.getValue();

:

int tmp = demo == null ? 1 : demo.getValue().intValue();
return (Integer) tmp;

int (not Integer) JLS, 15.25, (5.6.2). int NullPointerException.

+11
return demo==null?new Integer(1):demo.getValue();

- Integer, null - .

return demo==null?1:demo.getValue();

int, Integer . , NPE.

+3

All Articles