wood burning stoves 2.0*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Integer.MIN_VALUE" Watch "Integer.MIN_VALUE" New topic
Author

Integer.MIN_VALUE

Ismael Upright
Ranch Hand

Joined: Feb 15, 2007
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

Joined: Jan 22, 2008
Posts: 81
because +2147483648 is out of range for Int primitive


SCJP <br />SCWCD <br />SCBCD <br />SCEA-1
Ismael Upright
Ranch Hand

Joined: Feb 15, 2007
Posts: 166
don't call me primitive!
Vishal Matere
Ranch Hand

Joined: Jan 22, 2008
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

Joined: Feb 15, 2007
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

Joined: Jan 31, 2008
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

Joined: Mar 22, 2008
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.


There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Ismael Upright
Ranch Hand

Joined: Feb 15, 2007
Posts: 166
All clear now. Thenks guys for explaining that
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Integer.MIN_VALUE
 
Similar Threads
Math.abs()
Confused with the output
Simple code strange output aleast for me
~ operator
Why a & b are same ?