Java中128陷阱

执行下面的代码

public static void main(String[] args) {
       Integer a = 1000;
       Integer b = 1000;
       Integer c = 100;
       Integer d = 100;
	   Integer e = 99;
	   
       System.out.println(a==b);
       System.out.println(b==c);
       System.out.println(c==d);
       System.out.println(d==e);
    }

执行结果

false
false
true
false

自动装箱规范要求
boolean、byte、char<=127, -128<= short、int <=127 被包装到固定的对象中。

结果分析
根据自动装箱规范可知,1000超过了规范要求,所以a和b将不会被包装到一个Integer对象中,而是两个Integer对象,所以返回false;而100在规范要求范围内,所以c和d将会被包装到一个Integer对象中,故c和d会引用同一个Integer对象,指向同一个内存地址,所以返回true;b和c以及d和e都因为值都不相同,所以都被包装到两个不同的Integer对象中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值