Why does this code in Java output the value -210, when it's an infinite Loop?
Does this loop end when the integer reaches its max value?
public static void main(String[] args)
{
int a=100;
int b=110;
int c=0;
while(a>=100 && b<=110) {
a=a+1;
b=b-1;
c=a-b;
}
System.out.println(c);
}
This loop terminates due to integer overflow. When a reaches the max value of int, incrementing it makes it negative. When b reaches the min value of int, decrementing it makes it a large positive. Once one of them overflows, the loop terminates.
Due to the initial values, a would overflow first, since both are initialized to positive values, so a is closer to Integer.MAX_VALUE than b is to Integer.MIN_VALUE.
As to why the output it -210 :
a is incremented (Integer.MAX_VALUE-100)+1 times until the loop terminates
b is decremented the same number of times.
The final a is Integer.MIN_VALUE (due to overflow)
The final b is 110 - ((Integer.MAX_VALUE-100)+1) =
110 - ((-Integer.MIN_VALUE-1-100)+1) =
Integer.MIN_VALUE + 210
Hence, a-b ends up being Integer.MIN_VALUE - (Integer.MIN_VALUE + 210) = -210
Let me add to Eran's answer.
The variable a will wrap around when it reaches INT_MAX, and so does b when it reaches the negative of INT_MAX.
Which one reaches the limit first? a will.
Then the condition on a>=100 will fail, so the loop will finish.
At the time the loop finishes, the value of b will be 110 - (INT_MAX - 100).
Thus, c = a - b = -INT_MAX - ( 110 - (INT_MAX - 100) ) = 210;
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