-2

I have seen a weird version of the for loop where only (;;) is used to write something, for example:

            for (;;) {
                System.out.println("dabarkai");
            }

My guess is that it behaves similarly like a while(true) loop. But if there are some diferences in their actions then your more than welcome to share them here.

duh ikal
  • 161
  • 1
  • 8
  • 2
    it is sometimes also called `forever` (if the second expression, the condition, is not present (or it results in `true`), the loop will iterate - in this case for ever (unless terminated abruptly {Exception, break, return, ...}) –  Mar 05 '21 at 16:39
  • For loop to create an infinite loop – Kaustubh Khare Mar 05 '21 at 16:40
  • 5
    Note that this is not any sort of "special form" of for loop; this is just a regular for loop where the things in the header -- declarations of induction variables, termination condition, post-loop update -- are empty. Which degenerates to a termination condition of "never", no loop variables, and no post-loop update. – Brian Goetz Mar 05 '21 at 16:43
  • and it is exactly the same as `while (true)` - I *believe* compiler will generate same code –  Mar 05 '21 at 16:48

1 Answers1

0

It's an "infinite" loop, basically the same as while(true)

If you don't stop it manually (or by throwing Exception) it will run forever.

To stop it you can use return:

int i = 0;
for(;;) {
  i++;
  if(i == 10) {
    return;
  }
}
Benjamin M
  • 23,599
  • 32
  • 121
  • 201