[英]Whats the difference between the following 2 blocks of code in JAVA
Whats the difference between using 使用之间有什么区别
Object example1 = 3;
System.out.println(example1);
and 和
int example2 = 3;
System.out.println(example2);
Both print 3
, so what is the difference between using int
and Object
? 都打印3
,那么使用int
和Object
什么区别?
The first block wraps the literal value 3
in an Integer
object. 第一块将文字值3
包装在Integer
对象中。 While the second one assigns the literal value 3
to an int
variable. 而第二个将字面值3
分配给一个int
变量。
Both blocks should output 3
, there is nothing weird about that. 两个块都应输出3
,对此没有什么奇怪的。
3
is an int
, one of the native types in Java. 3
是int
,这是Java中的本机类型之一。
If you assign it to Object
it is auto-boxed into an Integer
which is a regular class. 如果将其分配给Object
它将自动装箱到作为常规类的Integer
中。
Therefore the difference is that in the first case you have in instance of the Integer
class stored in a variable of type Object
. 因此,不同之处在于,在第一种情况下,您将Integer
类的实例存储在Object
类型的变量中。 In the second case you have a primitive int
variable. 在第二种情况下,您有一个基本的int
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.