问:下面找奇数的代码段有问题吗?
boolean isOdd(int num) {
return num % 2 == 1;
}
答:没有考虑到负数问题,如果 num 为负则不正确。应该为 return num%2 == 0。
问:下面循环代码段有问题吗?
public static final int END = Integer.MAX_VALUE;
public static final int START = END - 2;
public static void main(String[] args) {
int count = 0;
for (int i = START; i <= END; i++) {
count++;
System.out.println(count);
}
}
答:这里无限循环的原因就是当 i 为 Integer.MAX_VALUE
时,此时 for 循环是先 ++,然后判断 i 是否 <=END,当 i 为 Integer.MAX_VALUE
再 ++ 时,i 变成了负数,所以就一直循环下去。变成负数的原因就是 int 溢出了。这里将 <=END 改成 <END 就可以解决问题。
问:下面代码段返回什么?
public static boolean decision() {
try {
return true;
} finally {
return false;
}
}
答:返回 false。此时 return true 是不可达语句,在编译阶段将优化去掉。
本文引用自 Java 中常见的一些陷阱问题知识点
网友评论