2018年11月13日Java学习之包装类,装箱与拆箱,

1.将八种基本数据类型定义相应的引用类型—包装类
这样做的好处就是可以调用类的方法了。
在这里插入图片描述

2.装箱与拆箱
装箱
int i = 500; Integer t = new Integer(i);
拆箱
boolean b = bObj.booleanValue();

1.5之后的版本支持自动装箱拆箱了。
举例
装箱以及装箱后的应用:
int i = 500;
Integer t = new Integer(i);
装箱:包装类使得一个基本数据类型的数据变成了类。
有了类的特点,可以调用类中的方法。
String s = t.toString(); // s = “500“,t是类,有toString方法
String s1 = Integer.toString(314); // s1= “314“ 将数字转换成字符串。
String s2=“4.56”;
double ds=Double.parseDouble(s2); //将字符串转换成数字

拆箱:
拆箱:将数字包装类中内容变为基本数据类型。
int j = t.intValue(); // j = 500,intValue取出包装类中的数据

包装类在实际开发中用的最多的在于字符串变为基本数据类型。
String str1 = “30” ;
String str2 = “30.3” ;
int x = Integer.parseInt(str1) ; // 将字符串变为int型
float f = Float.parseFloat(str2) ; // 将字符串变为int型

猜你喜欢

转载自blog.csdn.net/zcguoji/article/details/84035581