10行代码2道题,全答对的你月薪多少了?

题目1:

public static void demo01() {    Integer f1 = 100, f2 = 100, f3 = 200, f4 = 200;    System.out.println(f1 == f2);    System.out.println(f3 == f4);}

题目2:

private static Integer i;public static void demo02() {    if (i == 0) {        System.out.println("A");    } else {        System.out.println("B");    }}

|

|

|

|

|

|

|

|

|

|

题目1答案:

true

false

题目2答案:

NullPointerException

解析:

题目1:

以下是Integer类中“自动装箱”的源码:

public static Integer valueOf(int i) {    if (i >= IntegerCache.low && i <= IntegerCache.high)        return IntegerCache.cache[i + (-IntegerCache.low)];    return new Integer(i);}

其中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。

都答对了么?

本文分享自微信公众号 - 大数据和人工智能技术(Big_Data-AI)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论

暂无评论