1.什么是包装类
我们都知道,Java是oop的编程,但是我们八大基本数据类型中,如图下所示,是没有属性和方法的更加无法进行对象化的交互,所以应允而生了包装类;
2.基本数据类型和包装类的转化
2.1 装箱(基本数据类型-->包装类)
package com_imooc.baozhuanglei;
public class baozhuang_test {
public static void main(String[] args) {
//装箱
//1.自动装箱
int t =1;
Integer t1=t;
//2.手动装箱
Integer t2=new Integer(t);
}
}
2.2 拆箱(包装类-->基本数据类型)
package com_imooc.baozhuanglei;
public class baozhuang_test {
public static void main(String[] args) {
//装箱
//1.自动装箱
int t = 1;
Integer t1 = t;
//2.手动装箱
Integer t2 = new Integer(t);
//拆箱
//1.自动拆箱
int t3 = t2;
//2.手动拆箱
int t4 = t2.intValue(); //转换成为int数据类型
double t5 = t2.doubleValue(); //转换成为其他的数据类型
}
}
3.基本数据类型和字符串的转化
package com_imooc.baozhuanglei;
public class baozhuang_test {
public static void main(String[] args) {
//装箱
//1.自动装箱
int t = 1;
Integer t1 = t;
//2.手动装箱
Integer t2 = new Integer(t);
//拆箱
//1.自动拆箱
int t3 = t2;
//2.手动拆箱
int t4 = t2.intValue(); //转换成为int数据类型
double t5 = t2.doubleValue(); //转换成为其他的数据类型
//转换为字符串
String t6=Integer.toString(t2);
//字符转换成基本数据类型
int t7=Integer.parseInt(t6);
}
}
4.实例
package com_imooc.baozhuanglei;
public class zhuyi {
public static void main(String[] args) {
Integer a = new Integer(100);
Integer b = new Integer(100);
System.out.println("a==b的结果是:" + (a == b)); //a和b是通过new创建的不同对象所以指针不同,所以不相等
Integer c = 100;
System.out.println("c==100的结果是:" + (c == 100));//自动拆箱后的动作,所以相等
Integer d = 100;
System.out.println("c==d的结果是:" + (c == d));//在缓存区(对象池)中的数据,相比来说100=100
Integer e = 200;
Integer f = 200;
System.out.println("e==f的结果是:" + (e == f));//-128<缓存区(对象池)<127,超过了重新new对象,所以指针不同
}
}