Unknown NullPointerException in Java
<p>The following snippet uses simple Java code.</p>

<pre><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()));
    }
}
</code></pre>

<p>The above code works as expected with no problem and displays <code>Value = null</code> on the console.</p>

<p>In the following <code>return</code> statement,</p>

<pre><code>return demo==null?new Integer(1):demo.getValue();
</code></pre>

<p>since the object <code>demo</code> of type <code>Demo</code> is <strong>not</strong> <code>null</code>, the expression after <code>:</code> which is <code>demo.getValue()</code> is executed which invokes <code>getValue()</code> within the inner <code>Demo</code> class which returns <code>null</code> and finally, it is converted to String and displayed on the console.</p>

<p>But when I modify the <code>operations()</code> method something like the one shown below,</p>

<pre><code>private Integer operations()
{
    Demo demo = new Demo();    
    return demo==null?1:demo.getValue();
}
</code></pre>

<p>it throws <code>NullPointerException</code>. How?</p>

<hr>

<p>I mean when I use this <code>return</code> statement </p>

<pre><code>return demo==null?new Integer(1):demo.getValue();
</code></pre>

<p>it works (doesn't throw <code>NullPointerException</code>)</p>

<p>and when I use the following <strong>something similar</strong> <code>return</code> statement</p>

<pre><code>return demo==null?1:demo.getValue();
</code></pre>

<p>it causes <code>NullPointerException</code>. Why?</p>
