Java 中常见的一些陷阱问题知识点

问:下面找奇数的代码段有问题吗?

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是不可达语句,在编译阶段将优化去掉。

猜你喜欢

转载自blog.csdn.net/jiahao1186/article/details/84669395