您好,欢迎访问一九零五行业门户网

Java 编程实例题目分析

题目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。
以上就是java 编程实例题目分析的详细内容。
其它类似信息

推荐信息