Learning JAVA, i was trying to test the upper limit of while
loop which goes on incrementing an int
.Please see the program below :
public class Test {
public static int a(){
int a = 10;
while(a > 9 )
++a;
return a;
}
public static void main(String[] argc) {
Test t = new Test();
int k = t.a();
System.out.println("k = "+(1 * k));
}
}
I am aware that 32 bits range is from -2,147,483,648 to 2,147,483,647, so on the basis of that, i was expecting output as 2,147,483,647
but instead i am getting :
k = -2147483648
I even tried
System.out.println("k = "+(1 * k/2));
but still output is :
k = -1073741824
Question :
Why is solution negative when it should be positive?
You are incrementing your a
int
by 1
until it reaches 1 + Integer.MAX_VALUE
, which shifts its value to -2147483648 == Integer.MIN_VALUE
.
Here's your loop commented:
// "infinite" loop as a is assigned value 10
while(a > 9)
// when a reaches Integer.MAX_VALUE, it is still incremented by 1
++a;
// loop condition now false, as value for a has shifted to -2147483648
return a;
What is happening is called integer overflow.
Maximum 32-bit integer value in binary is:
0111 1111 1111 1111 1111 1111 1111 1111
When you add 1 to this number you get:
1000 0000 0000 0000 0000 0000 0000 0000
This is the twos compliment, or -2,147,483,648. Since any negative number is less than 9, the while loop exits.
You increment the value until it reaches the positive limit and it becomes all bits but the sign bit becomes 1.
0x7FFFFFFF = 01111111 11111111 11111111 11111111
This is binary representation of 2147483647, which is INT_MAX. When you increment it by one once again, it becomes
0x80000000 = 10000000 00000000 00000000 00000000
which is equal to INT_MIN, -2147483648.
Now,
2147483647 is greater than 9 so your loop continues. One more increment and oops, suddenly it is -2147483648 which is smaller than 9. This is the point where your loop condition fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With