2.int、char、long各占多少字节数
基本数据类: byte boolean 1个字节
short char 2个字节
int float 4个字节
long double 8个字节
3.int与integer的区别
通过代码来说明一下:
int i1 = 1;
Integer i2 = 1;
Integer i3 = new Integer(1);
System.out.println(i1 == i2);//true
System.out.println(i1 == i3);//true
在jdk5以后,java提供了自动装箱和拆箱的语法糖。
自动装箱就是: Integer i2 = 1;
这条语句其实在编译器编译后会变成 Integer i2 = Integer.valueOf(1);
将基本数据类型转换成包装数据类型
自动拆箱就是:编译后调用Integer.intValue();
将包装类型装换为基本数据类型。
所以前两条打印为true;
Integer i3 = new Integer(1);
Integer i4 = new Integer(1);
System.out.println(i3 == i4);//false
//这两个不相等的原因是:i3 i4 都是引用数据类型,
//分别new了不同的对象,指向的地址不一样。
Integer i2 = 1;
Integer i3 = new Integer(1);
Integer i7 = 127;
Integer i8 = 127;
Integer i9 = 128;
Integer i10 = 128;
System.out.println(i2 == i3);//false
System.out.println(i7 == i8);//true
System.out.println(i9 == i10);//false
首先看Integer类中的两个方法:
1.valueOf();自动装箱时使用
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
2.IntegerCache缓存
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之间的数值。
所以
i2 == i3为false的原因是:i2指向了缓存的数组(常量池)
i3则是重新new了一个对象,指向堆。
i7 == i8为true的原因是:i7和i8都是从数字中取得值,
指向的地址相同。
i9 == i10为false的原因:i9 和i10的值不在-128到127的
范围之内,则必须从新new对象,所以指向地址肯定不同了。