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

前端 未结 12 1386
走了就别回头了
走了就别回头了 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:21

    I think you should use something like this and it is called Upcasting:

    public int multiplyBy2(int x) throws ArithmeticException {
        long result = 2 * (long) x;    
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
            throw new ArithmeticException("Integer overflow");
        }
        return (int) result;
    }
    

    You can read further here: Detect or prevent integer overflow

    It is quite reliable source.

提交回复
热议问题