Question 1:
public static void demo01() {
Integer f1 = 100, f2 = 100, f3 = 200, f4 = 200;
System.out.println(f1 == f2);
System.out.println(f3 == f4);
}
Question 2:
private static Integer i;
public static void demo02() {
if (i == 0) {
System.out.println("A");
} else {
System.out.println("B");
}
}
Question 1 answer:
true
false
Answer to question 2:
NullPointerException
Analysis:
Question 1:
The following is the source code of "autoboxing" in the Integer class:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
The value of IntegerCache.low is -128, and the value of IntegerCache.high is 127. That is to say, when Integer is automatically boxed, if the range of the integer value is judged to be between [-128,127], the value in the integer constant pool will be used directly; if it is not in this range, a new Integer() will be created . Therefore, f1 and f2 in this question are both in the range of [-128,127] and use the same value in the constant pool. However, f3 and f4 are not in the range of [-128,127], and their values are both new, so f3 and f4 are not the same object.
Question 2:
The default value of Integer i is null. When i==0 is executed, the right side of the equal sign is a number, so in order to perform comparison operations, Integer will be automatically unboxed (that is, Integer will be converted to int type). Obviously, if you unbox null (convert null to a number), a NullPointerException will be reported.
The above is the detailed content of Analysis of Java Programming Example Questions. For more information, please follow other related articles on the PHP Chinese website!