1

Possible Duplicate:
How does Java handle integer underflows and overflows and how would you check for it?
How is System.out.println(4*2147483647) equal to -4 in java?

I want to know why this holds:

2 * Integer.MAX_VALUE == -2

I'm look forward to your response.

Community
  • 1
  • 1

5 Answers5

6

You get this result because of an integer overflow: in a two's complement system of representing negative integers, taking the max value which is 011.....112 and multiplying it by 2 gives you 11.....1102, which corresponds to -2.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

That is because of the Integer overflow.

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

Integer.MAX_VALUE is 0x7FFFFFFF. Multiply by two and you get 0xFFFFFFFE (equivalent to shifting left one bit). This is a negative number (the first bit is 1) and is the binary representation of -2.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
1

This is because of two's complement, where the lef most bit is used to signify if a number is positive (0) or negative (1). So when you add max int by itself (equivalent of multiplfy by two), this happens:

  011111111111111111111111
+ 011111111111111111111111
__________________________
  111111111111111111111110

and 111111111111111111111110 represents -2.

Phu
  • 572
  • 3
  • 10
0

The MAX_VALUE of Int is 2^31 - 1 = 2147483647 = 0111 1111 1111 1111 1111 1111 1111 1111(binary number) the highest bit (here is the first bit 0, indicates the integer is a positive number, when 1 indicates negative.

(suppose the length of an integer is 4bytes), 2 * MAX_VALUE,in computer an integer by 2 times is left shift(operator << ) on bits, eg. 2 << 1 = 4; 2 << 2 = 8; so 0111 1111 1111 1111 1111 1111 1111 1111 << 1 become 1111 1111 1111 1111 1111 1111 1111 1110 which is equal to -2 in decimal.

lovaya
  • 445
  • 3
  • 3