Unboxing a null boxed object throws unexpected NullPointerException

mre picture mre · Feb 21, 2013 · Viewed 15.1k times · Source

If you run the following code,

public class Foo{
    public static void main(String[] args){
        int id = new Bar().getId(); // throws unexpected NullPointerException
    }

    private static class Bar{
        private final Integer id;

        public Bar(){
            this(null);
        }

        public Bar(Integer id){
            this.id = id;
        }

        public Integer getId(){
            return id;
        }
    }
}

you will get the following stacktrace,

Exception in thread "main" java.lang.NullPointerException
    at Foo.main(Foo.java:3)

How come there's no compiler warning or anything? IMHO it's a pretty nasty subtlety with unboxing, or maybe I'm just naive.


Adding on to the answer provided by @Javier, if you're using Eclipse, you need to do the following to enable this:

  1. Navigate to Window > Preferences > Java > Compiler > Errors/Warnings
  2. Expand Potential programming problems
  3. Toggle Boxing and unboxing conversions to either "Warning", or "Error"
  4. Tap "OK"

Answer

Javier picture Javier · Feb 21, 2013

I don't know what IDE are you using, but Eclipse has an option to enable warning on boxing and unboxing conversions. It is not possible to detect it as a null pointer access, since null is not immediatly unboxed, but via Bar.getId().

The expression of type Integer is unboxed into int
Foo.java line 3