Conversion from null to int possible?
<p>I know that when I read the answer to this I will see that I have overlooked something
that was under my eyes. But I have spent the last 30 minutes trying to figure it out myself
with no result.</p>

<p>So, I was writing a program in Java 6 and discovered some (for me) strange feature.
In order to try and isolate it, I have made two small examples.
I first tried the following method:</p>

<pre><code>private static int foo()
{
    return null;
}
</code></pre>

<p>and the compiler refused it: Type mismatch: cannot convert from null to int.</p>

<p>This is fine with me and it respects the Java semantics I am familiar with.
Then I tried the following:</p>

<pre><code>private static Integer foo(int x)
{
    if (x &lt; 0)
    {
        return null;
    }
    else
    {
        return new Integer(x);
    }
}

private static int bar(int x)
{
    Integer y = foo(x);

    return y == null ? null : y.intValue();
}

private static void runTest()
{
    for (int index = 2; index &gt; -2; index--)
    {
        System.out.println("bar(" + index + ") = " + bar(index));
    }
}
</code></pre>

<p>This compiles with no errors! But, in my opinion, there should be a type conversion error
in the line</p>

<pre><code>    return y == null ? null : y.intValue();
</code></pre>

<p>If I run the program I get the following output:</p>

<pre><code>bar(2) = 2
bar(1) = 1
bar(0) = 0
Exception in thread "main" java.lang.NullPointerException
    at Test.bar(Test.java:23)
    at Test.runTest(Test.java:30)
    at Test.main(Test.java:36)
</code></pre>

<p>Can you explain this behaviour?</p>

<p><strong>Update</strong></p>

<p>Thank you very much for the many clarifying answers. I was a bit worried because
this example did not correspond to my intuition. One thing that disturbed me was
that a null was being converted to an int and I was wondering what the result would
be: 0 like in C++? That would hae been very strange.
Good that the conversion is not possible at runtime (null pointer exception).</p>
