简体   繁体   English

JAVA中以下2个代码块之间有什么区别

[英]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 ,那么使用intObject什么区别?

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. 3int ,这是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM