0

I've been researching this for a while but can't seem to figure out why this loop doesn't terminate.

public class Test{
    public static void main (String [] args){
        for (int i = 11; i > 10; i++){
            System.out.println(i);}
    }
}

The variable is initialized at a value that meets the requirements for the loop to terminate, so shouldn't there be no output whatsoever?
Sorry if this is a noob question but I can't seem to find the answer from searching (or maybe im just not wording the quesiton appropriately when i search)
The loop just keeps executing until I press ctrl+c.
Thanks in advance.

user2333867
  • 35
  • 1
  • 1
  • 5
  • 1
    Loops in java keeps going while the condition is true, not until the condition is true, so the loop will continue until it [overflows](http://stackoverflow.com/questions/3001836/how-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo) to `Integer.MIN_VALUE`. – Mike Samuel Apr 29 '13 at 22:27

3 Answers3

1

The second code fragment in a for loop (here, i > 10) is a boolean expression that, if true, lets the loop run again. It's obviously true all the time (until integer overflow).

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • oh okay. I was under the impression that the loop was supposed to terminate when i was greater than 10, not the other way around. haha excuse my ignorance please. new to this. Thanks to those who helped. – user2333867 Apr 29 '13 at 22:34
1

Your loop starts with i = 11, continues while i > 10 == true and at each iteration performs i++

Do you see how it doesn't terminate now?

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
1

The loop will never end, the end condition states that the loop will stop when i <= 10, and given that i = 11 at the beginning, the condition will evaluate to 11 > 10 == true, entering into an infinite loop.

Well, strictly speaking it will end after the index overflows, but it'll take a long while to reach that point.

Óscar López
  • 232,561
  • 37
  • 312
  • 386