0

Why is it that I can add 1 to already a max value of int? The output of this code is -2147483648. Isn't this only possible if type of biggerValue is a long? Guess not?

public class Test {
    public static void main (String[] args) {
    AddOne addOne = new AddOne();
    System.out.println("The value of bigger is " + addOne.plusOne()); 
    }
}

class AddOne {
    public long plusOne() {
        int value = Integer.MAX_VALUE;
        int biggerValue = value + 1;
        return biggerValue;
    }
}
Timothy
  • 346
  • 6
  • 18

2 Answers2

4

You should think of the number in bits. One bit is accumulated and an overflow happens. Since integer is signed, one bit flows into the bit which is used as sign.

 01111111 11111111 11111111 11111111 Base10: Integer.MAX_VALUE
+00000000 00000000 00000000 00000001 Base10: 1
____________________________________
=10000000 00000000 00000000 00000000 Base10: -2147483648
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
kai
  • 6,702
  • 22
  • 38
3

The JLS 15.18.2 says:

If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331