File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Abnormal behaviour of Integer.MIN_VALUE

 
ajay mittal
Greenhorn
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew Brown.
 
Darryl Burke
Bartender
Posts: 5115
11
Java Netbeans IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic