How does Java handle integer underflows and overflows and how would you check for it?

前端 未结 12 1366
走了就别回头了
走了就别回头了 2020-11-21 06:40

How does Java handle integer underflows and overflows?

Leading on from that, how would you check/test that this is occurring?

12条回答
  •  爱一瞬间的悲伤
    2020-11-21 07:25

    Having just kinda run into this problem myself, here's my solution (for both multiplication and addition):

    static boolean wouldOverflowOccurwhenMultiplying(int a, int b) {
        // If either a or b are Integer.MIN_VALUE, then multiplying by anything other than 0 or 1 will result in overflow
        if (a == 0 || b == 0) {
            return false;
        } else if (a > 0 && b > 0) { // both positive, non zero
            return a > Integer.MAX_VALUE / b;
        } else if (b < 0 && a < 0) { // both negative, non zero
            return a < Integer.MAX_VALUE / b;
        } else { // exactly one of a,b is negative and one is positive, neither are zero
            if (b > 0) { // this last if statements protects against Integer.MIN_VALUE / -1, which in itself causes overflow.
                return a < Integer.MIN_VALUE / b;
            } else { // a > 0
                return b < Integer.MIN_VALUE / a;
            }
        }
    }
    
    boolean wouldOverflowOccurWhenAdding(int a, int b) {
        if (a > 0 && b > 0) {
            return a > Integer.MAX_VALUE - b;
        } else if (a < 0 && b < 0) {
            return a < Integer.MIN_VALUE - b;
        }
        return false;
    }
    

    feel free to correct if wrong or if can be simplified. I've done some testing with the multiplication method, mostly edge cases, but it could still be wrong.

提交回复
热议问题