views:

209

answers:

2

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());
    }
}
+11  A: 

You are right, uninitilized class variables in Java have default value assigned to them. Integer type in Java are not same as int. Integer is the wrapper class which wraps the value of primitive type int in an object.

In your case iVar is a reference to an Integer object which has not been initilized. Uninitilized references get the default value of null and when you try to apply the intValue() method on a null reference you get the NullPointerException.

To void this problem you need to make your reference variable refer to an Integer object as:

class Test{
 // now iVar1 refers to an integer object which wraps int 0.
 static Integer iVar1 = new Integer(0);

 // uninitilized int variable iVar2 gets the default value of 0.
 static int iVar2;

 public static void main(String...args) {
  System.out.println(iVar1.intValue()); // prints 0.
  System.out.println(iVar2); // prints 0.
 }
}
codaddict
Thanks codaddict. It makes sense now.
+1  A: 

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.

Jason Coco