我对Java中将null赋值给变量持怀疑态度。在我的程序中,我将null作为String str_variable = null;
赋值给字符串变量。出于学习目的,我将空整数变量赋值为int int_variable = null;
,它显示错误Add cast with Integer
。因此,将上述int声明重写为Integer int_variable = null;
。这不会显示错误。我不知道这两种申报的原因。
请告诉我两者之间的区别。
String str_variable = null;
int int_variable = null; // error.
Integer int_variable1 = null; // no error.
发布于 2012-02-27 14:02:36
String和Integer都是类,在某种程度上它们不是原生数据类型,这就是为什么你总是可以将null设置为初始值,但是对于int,你必须总是用一个数字来初始化它,找出它们合适的初始化值的一个好方法是在main()之外创建变量,例如String var1;Integer;然后在main()中使用System.out.println(var1);System.out.println(var2);来查看当你运行程序时,什么被放置作为初始值。
发布于 2012-02-27 13:56:36
int
是一个原语,Integer
是一个类。
请参阅http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
发布于 2012-02-27 13:56:55
int
是一个原语类型,Integer
是一个包装类,类型扩展Object
类。非引用对象可以是null
,但基元不能。这就是为什么你会收到一条错误消息,说你需要转换。
你可以使用像int num = (Integer) null;
这样的行,这就是强制转换的方式,但是当你试图在代码中的任何地方使用num
时,你会得到NullPointerException
,因为一个非引用(空)的Integer
对象不会持有/包装一个原始值。
https://stackoverflow.com/questions/9466149
复制