1.基本数据类型和对应的包装类
基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
2.装箱和拆箱的定义
(1).装箱:把一个基本数据类型 转化为 包装类的过程,它分为自动装箱和显式装箱;
(2).拆箱:把一个包装类 转化为 基本数据类型的过程,它分为自动拆箱和显式拆箱。
3.显式装箱和显式拆箱
(1).显式装箱
对于显式装箱都要调用 “.valueOf” 方法。
int a = 1 ;
Integer c = Integer.valueOf(a);
System.out.println(c);
(2).显式拆箱
对于显式拆箱没用固定调用哪个方法,而是对于每种基本数据类型都有其独有的拆箱方法。
Integer a = new Integer(6);
int c = a.intValue();
System.out.println(c);
Float f = new Float(3.5);
float s = f.floatValue();
System.out.println(s);
4.自动装箱和自动拆箱
可以看到在使用过程中,显式装箱和显式拆箱带来不少的代码量,所以为了减少开发者的负担,java 提供了自动机制(自动装箱和自动拆箱)。
(1).自动装箱
对于自动装箱,在字节码文件中可以看到其调用了一个方法“ .valueOf ”,而在代码中看不见调用的这个方法,这就是自动装箱。
int a = 1 ;
Integer b = a ;
System.out.println(b);
(2).自动拆箱
Integer a = new Integer(6);
int b = a;
System.out.println(b);
Float f = new Float(3.5);
float i = f;
System.out.println(i);
5.小试牛刀
问:其输出结果是?
public static void main(String[] args) {
Integer a = 66;
Integer b = 66;
Integer c = 222;
Integer d = 222;
System.out.println(a == b);
System.out.println(c == d);
}
答:代码中存在自动装箱,所以在代码底层调用了“ valueOf方法 ”,而此方法的取值范围为[-128,127],如果超出这个范围就要产生一个新的对象。