Home >Java >javaTutorial >Analysis of Java Programming Example Questions

Analysis of Java Programming Example Questions

WBOY
WBOYforward
2023-04-24 19:07:051007browse

Question 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>

Question 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>

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:

<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>

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete