NullPointerException
that is not evident from the line number. To reduce it to a simple testcase:package com.javahowto.test;In that line, it seems the only suspect is the variable
public class Project {
private Integer version;
public static void main(String[] args) {
Project project = new Project();
System.out.println(project.toString());
//NPE in the next line
int version = project.getVersion();
}
private Integer getVersion() {
return version;
}
}
project
. But if project
was null, the constructor, or project.toString()
should've failed, and the execution shouldn't reach project.getVersion()
.You may have noticed it's the autoboxing, the implicit cast from Integer to int that has caused NPE. This line
int version = project.getVersion();is really this at runtime:
int version = project.getVersion().intValue();
project.getVersion()
returned null and caused NPE. Unlike primitives, Integer and other wrapper types don't default to 0 when used as instance or class variables. With the autoboxing in JDK 5, primitives and their wrapper types are almost but not completely interchangeable.Tags: