Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Integer.MIN_VALUE

 
John Wolf
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone please explain the following: -

What happens when you try to compile and run the following class...


The answer is that it would print two same -ive numbers. I thought it might throw an OverFlowException since int range is -2147483648 to 2147483687.

TIA!
Sumit
 
Ariel Ortiz
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no OverflowException in the Java API. Java integer arithmetic does not produce overflows, I just quietly wraps around.

In your example, Integer.MIN_VALUE == -(2^31). In binary that value is

1000 0000 0000 0000 0000 0000 0000 0000

When a value is the operand of the unary minus operator, you just need to compute it�s two�s complement: change all ones to zeros, all zeros to ones, add one to that result, and ignore the carry that goes out of the 32nd bit. If you do this with the above value, you get the same value you started with.

...Ariel
 
John Wolf
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ariel! I get it now.

For all integer values x, -x equals (~x)+1.

Cheers!~
Sumit
 
Tony Morris
Ranch Hand
Posts: 1608
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic