您的位置:首页技术文章
文章详情页

Java基本类型作为局部变量和成员变量时的存储方式有何不同?

浏览:59日期:2023-11-14 18:43:24

问题描述

1、这个问题可能涉及到很多方面,我自己研究了一下,弄懂了一部分,但是有一部分还不清楚。先贴代码(Java版本1.8):

public class Test{ int abc1 = 127; Integer abd1 = 127; Integer abf1 = 127; Integer abe1 = new Integer(127); {System.out.print('1t');System.out.println(abc1==abd1);System.out.print('2t');System.out.println(abd1==abe1);System.out.print('3t');System.out.println(abc1==abe1);System.out.print('4t');System.out.println(abd1==abf1); } int abc2 = 128; Integer abd2 = 128; Integer abf2 = 128; Integer abe2 = new Integer(128); {System.out.print('5t');System.out.println(abc2==abd2);System.out.print('6t');System.out.println(abd2==abe2);System.out.print('7t');System.out.println(abc2==abe2);System.out.print('8t');System.out.println(abd2==abf2); } public static void main(String[] args){Test t =new Test(); }/*输出为:1 true2 false3 true4 true5 true6 false7 true8 false*/}

2、先说自己清楚的部分:第4个输出与第8个输出比较清楚。这是由于在Java堆中有一个用于存储 常用基本数据类型字面量 的常量池,这个常量池可以存储整型(-128到127),布尔型(没有double类型)。执行“Integer abd1=127”时,除了在堆中建立一个值为127的Integer对象外,还会在相应的常量池中存储一个127,然后,将这个Integer对象与常量池中的127关联起来;再执行“Integer abf1=127”时,除了创建对象外,同样将其与常量池中的127关联起来,因而比较二者返回的是true。128就不同了,由于超出了常量池的存储范围,比较的仅仅是两个Integer引用i1与i2,所以返回的是false。

3、我的问题是:对象成员变量中的int类型(非static,非final)是怎样存储的。也就是说,当新建一个Text对象t时,abc1(abc2与此类似)是直接存在栈里还是包装后存在堆里,为什么会出现1-3(或5-7)返回是“true,false,true”的情况。

问题解答

回答1:

一 int和Integer比较时,Integer会自动拆箱后与int比较二 对象实例变量分配在堆上1和5比较 由于Integer类型自动拆箱所以为truenew Integer(xxx) xxx即使在缓存范围之内也会建立新的对象 所以2是false

标签: java
相关文章: