MEC@JavaSE@基础篇@笔记12@基本类型的封装类——自动拆箱与装箱

it2024-01-24  68

Java中的八大基本数据类型:

byte、char、short、int、long、float、double、boolean。

与这八种基本类型对应,Java提供了8中类类型:

Byte、Character、Short、Integer、Long、Float、Double、Boolean。

后面的八种类型为类的概念,使用时,与要遵守类的使用原则,比如,需要new关键字申请空间。

但是,java在1.5版本中增加了“自动拆箱与装箱”的功能。所谓“自动拆箱与装箱”就是对于int类型的数据,可以再需要是自动转换成Integer类型的对象,反之亦然。

示例代码:

public class AboutBaseType { public static void main(String[] args) { int one = 3; int another = fun(one); } private static int fun(Integer num) { return ++num; } }

注意:在main方法中,one是int类型变量,而fun()方法中的形参类是Integer的类类型的;主方法中调用fun()方法,直接传递的是one,这里无需将one转换成Integer对象,反之亦然。

本次示例代码对其他7中基本数据类型同样适用。

 

 

 

 

 

 

 

最新回复(0)