我的理解之基本类型与常量池
这里只以int类型为例,其他的我还没尝试。
package com.yddata;
public class Test {
public static void main(String[] args) {
int a = 32767;
int b = 32768;
}
}
我们编译该代码,然后使用javap来查看虚拟机字节码的指令获得如下内容
javap -verbose Test
我们暂时只看这一块
处理32767时,可以看到指令
sippush --将一个短整型常量值(-32768-32767)推送至栈顶
istore_1 --将栈顶int型数值存入第2个本地变量(0为第1个)
看一看到这里并没有去常量池里取数据,而是直接从栈里获取数据。
处理32768的时候,我们看到用了ldc
ldc: 将int、float或者String型常量值从常量池中推送至栈顶
我用-32767和-32769页进行了测试,结果和我预想的是一样的。
所以,综上所说,当int的值在 短整型常量值(-32768-32767)范围内的时候,int值存放在栈中,若超过这个范围,那么就会放到常量池中。
那么Integer呢? 是不是也是这样的呢。
我们也可以试一下,结果如下:
package com.yddata;
public class Test {
public static void main(String[] args) {
Integer c = 32767;
Integer d = 32768;
}
}
package com.yddata;
public class Test {
public static void main(String[] args) {
Integer c = -32767;
Integer d = -32769;
}
}
结果也是一样的啊。
有人会说,我在网上看到的Integer的类型说值在-128-127范围内才回被放到常量池的。
我的理解是,这个常量池和上面说的常量池是不一样的常量池。这里的-128-127其实是Integer的自身的一个常量池。
我们看到Integer的valueOf方法中是这么写的
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这里low的职位-128 high为127,在这个范围时,将他们放入了IntegerCache的cache数组中,不在这个范围,则重新new一个Integer对象。
所以这里是用的Integer的本身的常量池。不是虚拟机内存中说的常量池。
以上内容是我自己测试出来的结果,如果哪位大牛觉得不对,欢迎一起探讨,共同进步!