Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unboxing a null boxed object throws unexpected NullPointerException

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"
like image 880
mre Avatar asked Feb 20 '13 23:02

mre


1 Answers

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

like image 118
Javier Avatar answered Sep 30 '22 02:09

Javier