Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# "int" variable value calculation?

Anupama Dande
Greenhorn
Posts: 10
When I am executing the following code I am getting result as -2147483646 . I just want to know how p is calculated?
class Test
{
public static void main(String[] args)
{
int i = 2147483647, j = 1,k = 2;
int p = i + j + k;
System.out.println(p);
}
}
Anu.

Michael Morris
Ranch Hand
Posts: 3451
The maximum decimal value that can be represented by an int is 2^31 - 1 or 2147483647 which in binary is 01111111111111111111111111111111. Note that every bit is on except for the first bit which is the sign bit. Now let's add 3 to it which is 00000000000000000000000000000011.

Now note that the first bit is set which indicates that we now have a negative int. Negative integral types (byte, short, int and long) are stored in 2's complement form which means that you just turn all 0s to 1s and all 1s to 0s and add 1. So, to figure the negative value we subtact 1 and complement.

That value in decimal is 2147483646 and since the sign bit is set it becomes -2147483646.
[ July 08, 2003: Message edited by: Michael Morris ]

Steve Morrow
Ranch Hand
Posts: 657
Remember that all integers in Java are dealt with in binary (two's complement). So, your first number (2147483647) in binary format looks like this:
01111111 11111111 11111111 11111111
When you add one to that, using binary addition, you get the following 32-bit number:
10000000 00000000 00000000 00000000
Java looks at this as a "two's complement" binary number with that leftmost "1" representing the sign; "0" is positive, "1" is negative. Without getting into too much detail on conversion, the decimal value of that number is -2147483648. When you add two to this, you get the following 32-bit number:
10000000 00000000 00000000 00000010
... which, is -2147483646 in decimal.
(Ack! I'm too slow!)
[ July 08, 2003: Message edited by: Steve Morrow ]

Anupama Dande
Greenhorn
Posts: 10
Thank u all for ur assistance.