0

Why can't you place a print statement after this type of for loop? I don't understand what's going on. I understand this is not the standard way to write a for loop. So I was experimenting with this code because I saw this code somewhere. I just don't understand why you can't place the print statement at the end.

public class Test{

public static void main(String [] args){    
    for( ; ; ) {
        int x = 0;
        if (x < 5) {
            System.out.print(x + " ");
            x++;
        }
    }
    System.out.println("The End"); //This line will not compile.
}

}

2 Answers2

1

for( ; ; ) is same as while(true) and since you are not breaking this loop anywhere you created infinite loop.

So any code placed after such loop will never be executed (will be unreachable/dead code) and compiler informs you about this problem since such situation most probably wasn't your intention.

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

The loop never ends. You need to break it somewhere. Its like a while(true) like this. You can refactor a for(pre, cond, after){code} do a while

pre
while(cond)
{
    code
    after
}

so if you do for (;;) it's basically like a while(true).

bemeyer
  • 6,154
  • 4
  • 36
  • 86