7/18/2006

NullPointerException and autoboxing

I recently came across a NullPointerException that is not evident from the line number. To reduce it to a simple testcase:

package com.javahowto.test;

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;
}
}
In that line, it seems the only suspect is the variable 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.

3 comments:

Javin @ FIX Protocol Tutorial said...

Hi,
Autoboxing is a great feature provided by JAVA5 but using it blindly may result in very subtle problem which will take hours and hours to
debug and find. to read more see the link
What is the problem while using '==' in autoboxing world in Java 5 ?

Thanks
Javin

pramod sharma said...

i think u should first set the value of version then retrieve it using getversion method .(version is havig null refrence thats its throwing null pointer exception)

Anna said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions








Java Course in Chennai

Java Online Training India