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
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.