Why does this for loop work [closed]

As others have pointed in the comments, there are a few issues on top of the loop issue. First, the third semicolon is a syntax error. Second, it’s supposed to be k-=2 instead of k=-2 or the loop will never end.

Once those are cleared, this code is equivalent to:

int k;
for (k=0; k>-3; k-=2);

{
  System.out.println(k);
}

Which is the same as:

int k;
for (k=0; k>-3; k-=2);

System.out.println(k);

Which is the same as:

int k;
for (k=0; k>-3; k-=2) {
}

System.out.println(k);

By using a semicolon after the for loop you asked for a for loop that does nothing. The brackets around System.out.println(k) after that are just normal brackets. You can put any code in its own scope, even without a for loop.

Leave a Comment