类和接口是对象类型,但是基本数据类型不是对象类型。但是,
为什么下列代码看起来,对象可以直接赋值给基本数据类型,而值可以直接赋值给类?
代码能够正常运行正是因为包装类的自动装拆箱。
什么是包装类?
包装类(Wrapper Class)是指一种将基本数据类型(如int、float、char等)包装成对象的类。在Java中,每种基本数据类型都有对应的包装类,它们用于在对象中存储基本类型的值。
主要的包装类及其对应的基本数据类型如下:
1.Integer:int
2.Float:float
3.Character:char
4. Boolean:boolean
5.Double:double
6.Byte:byte
7.Short:short
8.Long:long
包装类的特点:
1.不可变性:包装类的实例是不可变的,一旦创建就无法修改其值。任何修改值的操作都会创建一个新的对象。
2.自动装箱与拆箱:Java提供了自动装箱(Autoboxing)和自动拆箱(Unboxing)的功能,可以在基本数据类型和对应的包装类之间自动转换。
装箱和拆箱:
1.装箱:将基本数据类型变为包装类型。
2.拆箱:将包装类中包装的基本数据类型取出。
package com.jsu.java;
public class Demo001 {
public static void main(String[] args) {
// Integer integer = new Integer(1);
// int n = integer;//自动装箱
// Integer integer1 = 1;//自动拆箱
Integer integer = new Integer(1);//手动装箱
int n = integer.intValue();
Integer integer1 = new Integer(1);//手动拆箱
}
}
知识补充:
public class Demo001 {
public static void main(String[] args) {
Integer i1 = 10;
Integer i2 = 10;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
为什么取不同的数据大小会出现不同的结果?
valueOf源码分析:
public static Integer valueOf(int i) {
assert IntegerCache.high>= 127;
if (i >= IntegerCache.low&& i <= IntegerCache.high)
return IntegerCache.cache[i+ (-IntegerCache.low)];
return new Integer(i);
}
通过查看原码可知,java针对-128-127之间的数据做了一个特殊处理。
如果数据不在该范围内的,就new一个新的对象。
如果数据在该范围内,就不new新的对象,而是调用底层的缓冲数组 。