0

I though that the following pieces of code does not compile. However after running it I got unexpected result, I don't understand how it is printing -2 ? can you explain how addition is done here?

int x = 2147483647+2147483647; // it compiles
System.out.print(x); // prints -2

any explain is welcome

The Scientific Method
  • 2,374
  • 2
  • 14
  • 25

1 Answers1

1

Short answer: When Java integers reach their maximum value plus one, they start at their minimum again. It's like going in a circle.

It's like that due to the technical representation of integers as bits. Imagine having 3 bits available to represent a number. You could have the number 111. If you add 1 to it, you'll end up at 1000 but since you only have 3 bits available, it cuts off the first and you end up with 000 which is why you're at the minimum value again after adding 1 to the maximum.

Philipp
  • 520
  • 3
  • 7
  • explain how it got it '-2'? – The Scientific Method Feb 13 '20 at 13:37
  • @TheScientificMethod he did. – Stultuske Feb 13 '20 at 13:39
  • 1
    I added a simple technical explanation to my answer. Java integers are stored as bits, actually 64 bits where the smaller half are negative and the bigger half positive numbers. That`'s not a mystery and for a deeper explanation, you should google how Java internally handles integers. – Philipp Feb 13 '20 at 13:41
  • Really the logic is different. Max value you can assign to an integer is 2147483647. The binary form for this value is 1111111111111111111111111111111. Adding one you get 10000000000000000000000000000000 and according to your logic the result should be 0. Instead printing the result of "2147483647+1" you get -2147483648. So going over the limit the representation will be in "decimal from signed 2's complement" and not "decimal". Converting the result of 2147483647+2147483647 in binary you get 11111111111111111111111111111110 that converted in decimal from signed 2's complement is equal to -2. – gregorycallea Feb 13 '20 at 14:13