Win a copy of Design for the Mind this week in the Design forum!

# Integer.MIN_VALUE

Ismael Upright
Ranch Hand
Posts: 166
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
because +2147483648 is out of range for Int primitive

Ismael Upright
Ranch Hand
Posts: 166
don't call me primitive!

Vishal Matere
Ranch Hand
Posts: 81
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
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
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
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
All clear now. Thenks guys for explaining that