This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Abnormal behaviour of Integer.MIN_VALUE Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Abnormal behaviour of Integer.MIN_VALUE" Watch "Abnormal behaviour of Integer.MIN_VALUE" New topic
Author

Abnormal behaviour of Integer.MIN_VALUE

ajay mittal
Greenhorn

Joined: Nov 23, 2011
Posts: 24
Hi All,

I used the following statements in main function:-

System.out.println(Integer.MIN_VALUE);
System.out.println(-(Integer.MIN_VALUE));

Output:
-2147483648
-2147483648

While obtaining the negative of a negative number i am still getting a negative number. Can anyone let me know the reason for this behaviour.

regards,
Ajay
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4338
    
    7

The range that ints can have in Java is -2147483648 to 2147483647. Notice the final digit there.

So, -(-2147483648) is +2147483648, but that's too big to store in an int variable. So you get an overflow, and the value wraps round to the bottom of the range again.
ajay mittal
Greenhorn

Joined: Nov 23, 2011
Posts: 24
Thanks Matthew Brown.
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4523
    
    5

This is actually mentioned in The Java™ Language Specification
For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown.


luck, db
There are no new questions, but there may be new answers.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Abnormal behaviour of Integer.MIN_VALUE
 
Similar Threads
absolute method in mathclass
abs() method of Math class
Math.abs Confusion
absulate method
How is -Integer.MIN_VALUE Equal to Integer.MIN_VALUE