Home> Java> javaTutorial> body text

Analysis of Java Programming Example Questions

WBOY
Release: 2023-04-24 19:07:05
forward
938 people have browsed it

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);
}
Copy after login

Question 2:

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

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);
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!