If you run the following code,
public class Foo{
public static void main(String[] args){
int id = new Bar().getId();
}
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