题目1:
<code>public static void demo01() {<br/> Integer f1 = 100, f2 = 100, f3 = 200, f4 = 200;<br/> System.out.println(f1 == f2);<br/> System.out.println(f3 == f4);<br/>}</code>题目2:
<code>private static Integer i;<br/>public static void demo02() {<br/> if (i == 0) {<br/> System.out.println("A");<br/> } else {<br/> System.out.println("B");<br/> }<br/>}</code>题目1答案:
立即学习“Java免费学习笔记(深入)”;
true
false
题目2答案:
NullPointerException
解析:
题目1:
以下是Integer类中“自动装箱”的源码:
<code>public static Integer valueOf(int i) {<br/> if (i >= IntegerCache.low && i <= IntegerCache.high)<br/> return IntegerCache.cache[i + (-IntegerCache.low)];<br/> return new Integer(i);<br/>}<br/></code>其中IntegerCache.low的是值是-128,IntegerCache.high的值是127。也就是说,Integer在自动装箱时,如果判断整数值的范围在[-128,127]之间,则直接使用整型常量池中的值;如果不在此范围,则会new 一个新的Integer()。因此,本题f1和f2都在[-128,127]范围内,使用的是常量池中同一个值。而f3和f4不在[-128,127]范围内,二者的值都是new出来的,因此f3和f4不是同一个对象。
题目2:
Integer i 的默认值是null。当执行 i==0 时,等号右侧是数字,因此为了进行比较操作,Integer会进行自动拆箱(也就是将Integer转为int类型)。很明显,如果对null进行拆箱(将null转为数字),就会报NullPointerException。
以上就是Java 编程实例题目分析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号