为什么 Integer a=10 是 java 中的有效语句? [英] Why is Integer a=10 a valid statement in java?

查看:40
本文介绍了为什么 Integer a=10 是 java 中的有效语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Integer 是 int 的包装.所以必须创建一个对象来初始化 a 的值.

As far as I know, Integer is a wrapper class for int. So an object must be created for initializing value of a.

Integer x=new Integer(10);

但是 Integer x=10; 似乎工作得很好.有人可以解释一下吗?

But Integer x=10; seems to work perfectly. Can someone please explain how?

推荐答案

感谢自动装箱.

自动装箱是 Java 编译器在原始类型与其对应的对象包装类之间进行的自动转换.例如,将 int 转换为 Integer,将 double 转换为 Double,等等.如果转换方向相反,则称为拆箱.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

参见文档 https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

这篇关于为什么 Integer a=10 是 java 中的有效语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆