wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark ""int" variable value calculation?" Watch ""int" variable value calculation?" New topic

"int" variable value calculation?

Anupama Dande

Joined: May 09, 2003
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;
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
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 ]

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Steve Morrow
Ranch Hand

Joined: May 22, 2003
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

Joined: May 09, 2003
Posts: 10
Thank u all for ur assistance.
I agree. Here's the link: http://aspose.com/file-tools
subject: "int" variable value calculation?