How come javac
doesn't emit error on this code?
private static int compute(int v) {
return v == 0 ? null : v;
}
Surely, compute(0)
will throw NullPointerException
. I would expect the java compiler to prevent this by doing some basic static code analysis, just like it would prevent
private static int compute(int v) {
if (v == 0)
return null;
else
return v;
}
Why does java allow NPE?
To indicate an exceptional condition (and allow the programmer to potentially recover).
In your example, Java allows both autoboxing and unboxing. The null
boxes the int
to an Integer
(which is then unboxed to an int
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With