更新时间:2020-10-29 来源:黑马程序员 浏览量:
1、Integer是int的包装类,int则是java的一种基本数据类型 ;
2、Integer变量必须实例化后才能使用,而int变量不需要 ;
3、Integer实际是对象的引用,当new一个Integer时,实际上是生成一个指针指向此对象;而int则是直接存储数据值;
4、Integer的默认值是null,int的默认值是0;
问题一:
public static void main(String[] args) { Integer a = 100; Integer b = 100; System.out.println(a == b); Integer c = 200; Integer d = 200; System.out.println(c == d); }
请问:a==b的值以及c==d的值分别是多少?
答案: a==b为true; c==d为false
原因分析:
Integer a = 100;实际上会被翻译为: Integer a = ValueOf(100);
从缓存中取出值为100的Integer对象;同时第二行代码:Integer b = 100; 也是从常量池中取出相同的缓存对象,因此a跟b是相等的;而c 和 d
因为赋的值为200,已经超过 IntegerCache.high
会直接创建新的Integer对象,因此两个对象相⽐较肯定不相等,两者在内存中的地址不同。
问题二:
Integer a = 100; int b = 100; System.out.println(a == b);
Integer a = new Integer(100); int b = 100; System.out.println(a == b);
输出结果是什么?
答案为:ture,因为a会进行自动动拆箱取出对应的int值进行比较,因此相等。
问题三:
Integer a = new Integer(100); Integer b = new Integer(100); System.out.println(a == b);
输出结果是什么?
答案为:false,因为两个对象相比较,比较的是内存地址,因此肯定不相等。
问题四:
最后再来一道发散性问题,大家可以思考下输出的结果为多少:
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { Class cache = Integer.class.getDeclaredClasses()[0]; Field myCache = cache.getDeclaredField("cache"); myCache.setAccessible(true); Integer[] newCache = (Integer[]) myCache.get(cache); newCache[132] = newCache[133]; int a = 2; int b = a + a; System.out.printf("%d + %d = %d", a, a, b); }
答案为: 2 + 2 = 5. 大家可以下来好好思考下为什么会得到这个答案?
猜你喜欢:
【AI设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19【AI大模型开发-Python】毕业33个工作日,就业率已达到94.55%,班均薪资20763元
2025-09-19【AI智能应用开发-Java】毕业5个工作日就业率98.18%,最高薪资 17.5k*13薪,全班平均薪资9244元
2025-09-19