Unboxing a null-box object throws an 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 command,

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

Why are there no compiler warnings or anything else? IMHO this is a rather unpleasant subtlety with unpacking, or maybe I'm just naive.


By adding the answer provided by @Javier if you are using Eclipse, you need to do the following:

  • Go to Window> Preferences> Java> Compiler>Errors/Warnings
  • Expand Potential Programming Issues
  • Switch Boxing and unzip conversions to “Warning” or “Error”
  • Click OK
+5
6

, IDE , Eclipse . , null , Bar.getId().

Integer int Foo.java line 3

+5

, JDK & trade; 5.0 ,

.. int Integer, . Integer . autounbox null, NullPointerException.

+4

null -, null, NullPointerException.

[Integer object].intValue() ( ), NullPointerException, null .

, !

+3

NullPointerException - RuntimeException, IDE .

null .

int getId(){
    if(id!=null){
        return id;
    }
    // return other or throw a checked exception.
}
0

. :

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

. Bar null, . Bar id . Bar, Bar .

, , , int id Integer. :

private static class Bar{
    private final int id;

    public Bar(){
        this(0);
    }

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

    public int getId(){
        return id;
    }
}

( , :-))

0

Boxing is nothing more than syntactic sugar for casting an object, such as Integer, to the native equivalent of 'int'. Natives cannot be empty, but objects can. The boxing mechanism will not prevent NullPointerExceptions in these cases.

0
source

All Articles