I had a simple bit of code that was supposed to be an endless loop since x will always be growing and will always remain larger than j.
int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
x = x + y;
}
System.out.println(y);
but as is, it prints y and does not loop endlessly. I cannot figure out why. However, when I adjust the code in the following manner:
int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
x = x + y;
System.out.println(y);
}
System.out.println(y);
It becomes an endless loop and I have no idea why. Does java recognize its an endless loop and skip it in the first situation but has to execute a method call in the second so it behaves as expected? Confused :)
xgrows faster than the loop variablej. In other words,jwill never hit an upper bound, hence the loop will run "forever." Well, not forever, you'll get an overflow at some point most likely. – Tim Biegeleisen yesterdayy238609294 times – N00b Pr0grammer yesterdaySystem.out.println(x)instead ofyat the end would have showed instantly what the problem was – JollyJoker 18 hours ago