1

Possible Duplicate:
What does for (;;) mean in Java?

I am reading some Java API docs, and I have encountered this loop of a very strange perky look, which elated me to come here and ask what is it about. Would be glad to find it as soon as possible. Thank you on your upcoming efforts.

  public int read() throws IOException {
       synchronized (lock) {
          ensureOpen();
           **for (;;)** {
               if (nextChar >= nChars) {
                  fill();
                  if (nextChar >= nChars)
                       return -1;
               }
              if (skipLF) {
                     skipLF = false;
                  if (cb[nextChar] == '\n') {
                     nextChar++;
                      continue;
                   }
               }
             return cb[nextChar++];
          }
       }
    }
Community
  • 1
  • 1

4 Answers4

4

for(;;)

That is an infinite loop.

For example, it's equivalent to something like

while(true)

Naturally, to exit such a loop, a branching statement is used.

EDIT: clearly the use of the word "infinite" was a bad choice. Still, for all intents and purposes, a for(;;) loop does not terminate using the same conditional mechanism of typical for loops. I believe this was the point of the question. The comments are just splitting hairs at this point.

Tom
  • 18,685
  • 15
  • 71
  • 81
  • `for (;;) break;` is not infinite loop – amit May 09 '12 at 22:13
  • 4
    @amit, obviously a break changes things. – Tom May 09 '12 at 22:14
  • A `break`, `return`, or `throw` statements. The point is - an infinite loop is determined according to its content as well as its condition int `i = 0; while (i < 1) { } ` is an infinite loop, though the condition is not strictly `true`. – amit May 09 '12 at 22:15
  • 1
    what is more clean code like? for(;;) or while(true) ? – nexus May 09 '12 at 22:15
  • 1
    @nexus, it doesn't matter, they are essentially equivalent and *probably* produce the same bytecode. – Tom May 09 '12 at 22:17
  • @amit _as written_ it's an infinite loop. Changing the question in response to an answer is pedantry. – Tom Jul 11 '16 at 17:41
2
for(;;)

This is an infinte loop, no variables initialization, no condition to check, no incremental step ... only exits the loop when execute the "return" sentence inside conditions.

Common for loop:

for(int i = 0 ; i < max ; i++)

Hope helps.

chavocarlos
  • 351
  • 1
  • 8
1

It means that the condition of termination of the cycle is not expressed in the usual form.

The only ways to terminate the cycle are the two return statements.

Vitaly Olegovitch
  • 3,509
  • 6
  • 33
  • 49
0

As stated by @Tom, this is an infinite loop. Uses of this in your program could be if you would like to execute something forever.

RandellK02
  • 167
  • 1
  • 4
  • 17