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

青春壹個敷衍的年華 提交于 2019-12-03 22:57:11
codaddict

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.
 }
}

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.

SunilChandra M N
private Integer amount=Integer.valueOf(0);
private Integer points=Integer.valueOf(0);

In particular, why you should use Integer.valueOf(int) instead of new Integer(int): CACHING.

This variant of valueOf was added in JDK 5 to Byte, Short, Integer, and Long (it already existed in the trivial case in Boolean since JDK 1.4). All of these are, of course, immutable objects in Java. Used to be that if you needed an Integer object from an int, you’d construct a new Integer. But in JDK 5+, you should really use valueOf because Integer now caches Integer objects between -128 and 127 and can hand you back the same exact Integer(0) object every time instead of wasting an object construction on a brand new identical Integer object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!