Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java allow NPE

Tags:

java

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;
}
like image 269
milan Avatar asked Jan 17 '16 09:01

milan


1 Answers

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).

like image 88
Elliott Frisch Avatar answered Oct 05 '22 23:10

Elliott Frisch