I know that when I read the answer to this, I will see that I missed something; it was under my eyes. But the last 30 minutes I tried to figure it out myself without a result.
So, I wrote a program in Java 6 and discovered some (for me) strange functions. To try to isolate it, I made two small examples. First I tried the following method:
private static int foo() { return null; }
and the compiler abandoned it: Type of mismatch: cannot be converted from null to int.
This is good with me, and he respects the semantics of Java that I am familiar with. Then I tried the following:
private static Integer foo(int x) { if (x < 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 > -2; index--) { System.out.println("bar(" + index + ") = " + bar(index)); } }
This is a compilation without errors! But, in my opinion, there should be a type conversion error in the string
return y == null ? null : y.intValue();
If I run the program, I get the following output:
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)
Can you explain this behavior?
Update
Thanks so much for the many clarifying answers. I was a little worried because this example did not fit my intuition. One thing that bothered me was that null was converted to int, and I was wondering what the result would be: 0 like in C ++? That would be very strange. It is good that conversion is not possible at runtime (null pointer exception).
java
Giorgio Jul 05 2018-11-11T00: 00Z
source share