包装类:
1、Java中的基本类型都有其对应的封装,即包装类,简而言之就是将基本数据类型封装为一个对象。
2、对应的包装类大部分是基本数据类型的首字母大写,但是有特例,如:int—Integer,
char–Character。
3、包装类可以调用一些方法,而基本数据类型则无法调用。
4、基本数据类型的默认值为:整形:0; boolean:false; char:/u0000; 浮点型:0.0(f/d)而包装类的默认值为Null。
自动装箱与自动拆箱都是指包装类与其对应的基本类型之间的变化,是指Jdk更新后为程序员提供的一些简化操作,具体操作由jdk完成,所以有时会报一些代码表面上看不出来的错误。
测试代码:
package cn.ldedu;
public class BaoZhuang {
public static void main(String[] args) {
Integer a=1000; //自动装箱,编译器后台执行Integer a=new Integer(1000)
int b=a; //自动拆箱,可以将Integer类型直接赋给int型,后台操作int b=a.intValue(),当a为null时,则会报空指针错误
Integer c=1234;
Integer d=1234;
System.out.printf("c==d结果为 ",c==d); //因为是不同对象,所以false
System.out.printf("c.equals(d)结果为 %b",c.equals(d));
System.out.println();
System.out.println("**************************");
Integer e=123;
Integer f=123;
System.out.printf("e==f结果为 %b%n",e==f); //Integer类将[-128,127]之间的数仍然当作基本数据类型处理,所以为true
System.out.printf("e.equals(f)结果为 %b",e.equals(f));
}
}
运行截图: