This week's book giveaway is in the Design forum. We're giving away four copies of Building Microservices and have Sam Newman on-line! See this thread for details.

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.

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

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

Joined: May 09, 2003
Posts: 10

posted

0

Thank u all for ur assistance.

I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com