Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Integer.MIN_VALUE

 
Ismael Upright
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code from jqplus6:


public class TestClass
{
public static void main(String[] args) throws Exception
{
int a = Integer.MIN_VALUE;
int b = -a;
System.out.println( a+ " "+b);
}
}



It will print two same negative numbers.

Why???
 
Vishal Matere
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because +2147483648 is out of range for Int primitive
 
Ismael Upright
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
don't call me primitive!
 
Vishal Matere
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ha ha ,
Classic example of mis-understanding.
i meant to say , 'Int primitive' NOT 'Int, primitive' (see comma) ...

primitive adjective was for Int and not for you.


V
 
Ismael Upright
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see


But I don't understand how it come that because +2147483648 is out of range for Int primitive, the code I stated printed two negative numbers


Shouldn't we receive some kind of error or exception?
[ May 11, 2008: Message edited by: Ismael Upright ]
 
Wim Molenberghs
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because the max positive integer is not 2147483648 but 2147483647 because the 0 is also considered a positive int.
so if you have an int of 2147483648, it is out of range.
The couter of int goes:
2147483646
2147483647
-2147483648
-2147483647
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ismael,

This is explicity addressed in the Java Language Specification for the Unary Minus Operator -:


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. For all integer values x, -x equals (~x)+1.
 
Ismael Upright
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All clear now. Thenks guys for explaining that
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic