This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Integer.MIN_VALUE Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Integer.MIN_VALUE" Watch "Integer.MIN_VALUE" New topic


John Wolf
Ranch Hand

Joined: Feb 18, 2002
Posts: 64
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.


SCJP 1.2, SCJP 1.4, SCJA, SCWCD 1.4<br /> <br />------------------------------<br />
Ariel Ortiz
Ranch Hand

Joined: May 14, 2004
Posts: 121
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.

John Wolf
Ranch Hand

Joined: Feb 18, 2002
Posts: 64
Thanks Ariel! I get it now.

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

Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

Tony Morris
Java Q&A (FAQ, Trivia)
Have you checked out Aspose?
subject: Integer.MIN_VALUE
It's not a secret anymore!