I am new to Java. I just read that class variables in Java have default value.
I tried the following program and was expecting to get the output as 0
, which is the default value on an integer, but I get the NullPointerException
.
What am I missing?
class Test{
static Integer iVar;
public static void main(String...args) {
System.out.println(iVar.intValue());
}
}
You are right, uninitialized class variables in Java have default value assigned to them.
Integer
type in Java are not same asint
.Integer
is the wrapper class which wraps the value of primitive typeint
in an object.In your case
iVar
is a reference to anInteger
object which has not been initiliazed. Uninitialized references get the default value ofnull
and when you try to apply theintValue
() method on a null reference you get theNullPointerException
.To avoid this problem altogether you need to make your reference variable refer to an
Integer
object as:It means that
iVar
is null. In java, you can't invoke methods on a null reference, it generates the NullPointerException that you are seeing.