Integer x = null;
System.out.println(2 * x);
运行结果:
Exception in thread “main” java.lang.NullPointerException
这是因为x在与2进行相乘之前会先进行自动拆箱
即 x.intValue()
因为x是null,所以会引发空指针异常。
对于八大基本类型,他们都有相应的包装类。并且包装类都是用final修饰的,无法再派生子类。
那么为什么会有包装类呢?因为有时需要将基本类型装换为对象。
以下是int的包装类Integer
public final class Integer extends Number implements Comparable<Integer> {
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*/
@Native public static final int MIN_VALUE = 0x80000000;
...
...
...
}
所有的数值基本类型包装类的超类都是Number类(除了Character和Boolean)
以下演示装箱和拆箱
将int类型变换为Integer类型为装箱
相反,将Integer类型转换为int类型的拆箱
Integer x = 110;
int t = 110;
Integer tt = Integer.valueOf(t);//装箱
int xx = x.intValue();//拆箱
Integer装箱源码
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Integer拆箱源码
private final int value;
public int intValue() {
return value;
}
看一段代码:
Integer a1 = 128;
Integer a2 = 128;
System.out.println(a1 == a2);
a1 = 127;
a2 = 127;
System.out.println(a1 == a2);
我们都知道 == 比较的是对象在内存中的位置
那么这两个 输出的答案是什么呢?
false
true
为什么会这样呢?
128相比较不相等 肯定是因为在内存中创建了两个新的Integer对象。
127不相等则是因为Integer中的这段代码
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
可以看出,Integer类一实例化,就会将[-128,127]中所有的数在静态块中进行缓存操作,也就是这个范围内的数已经给你包装好了,你只需要将引用指向这个对象就行了,所以,在比较利用==比较127时,其实比的是用一个对象的两个不同名称的引用罢了。