Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does using a default-valued Java Integer result in a NullPointerException?

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());
    }
}
like image 747
user292844 Avatar asked Mar 13 '10 07:03

user292844


People also ask

What is the default value of int and Integer in Java?

int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.

What's the default value of an integer?

The default value of Integer is 0.

What type is null Java?

In Java programming, null can be assigned to any variable of a reference type (that is, a non-primitive type) to indicate that the variable does not refer to any object or array.


1 Answers

You are right, uninitialized 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 initiliazed. Uninitialized 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 avoid this problem altogether 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);

 // uninitialized 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.
 }
}
like image 74
codaddict Avatar answered Nov 04 '22 00:11

codaddict