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

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

    It wraps around.

    e.g:

    public class Test {
    
        public static void main(String[] args) {
            int i = Integer.MAX_VALUE;
            int j = Integer.MIN_VALUE;
    
            System.out.println(i+1);
            System.out.println(j-1);
        }
    }
    

    prints

    -2147483648
    2147483647
    

提交回复
热议问题