How come the below code prints "The value of J is: 1000"?
I would've thought that the "j != 1000" would evaluate to false in all instances (Because 1000 mod 19 is not 0), hence making it an infinite loop.
public static void loop2() {
int j = 0;
for(int i=0;j != 1000;i++) {
j = j+19;
}
System.out.println("The value of J is: " + j);
}
Max value of int in java is 2,147,483,647
on adding 19 to j, again and again, this value will be passed. After which it will start again from min value of int i.e. -2,147,483,648
.
This will continue until the value of j become 1000 at some point. Hence, the loop will stop.
j
will iterate 17 times over the max value of the integer to reach this point. Code for checking:
public class Solution {
public static void main(String args[]) {
int j = 0;
int iterationCount = 0;
for(int i=0;j != 1000;i++) {
j = j+19;
if(j - 19 > 0 && j < 0) {
iterationCount ++;
}
}
System.out.println("The value of J is: " + j + " iterationCount: " + iterationCount);
}
}
Output:
The value of J is: 1000 iterationCount: 17
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