Why must a variable be declared in a for loop initialization?

If v is declared prior to the loop, you should leave the first part of the for statement empty:

int v = 0;

for (; v < 2; v++) {
    ...
}

There's no meaning to just writing v;.


Your loop declaration is valid if you remove the extraneous v in the declaration (assuming v was declared beforehand):

Change it to for(; v < 2; v++)

All three modifiers in the traditional for loop are optional in Java.

Alternatives examples:

Below is the same as a while (true) loop:

for (;;) {

}

Adding extra increments:

int j = 0;
for (int k = 0; k < 10; k++, j++) {

}

Adding extra conditions to terminate the loop:

int j = 0;
for (int k = 0; k < 10 || j < 10; k++, j++) {

}

Declaring multiple of the same type variable:

for (int k = 0, j = 0; k < 10 || j < 10; k++, j++) {

}

And obviously you can mix and match any of these as you want, completely leaving out whichever ones you want.


According to the java doc

The general form of the for statement can be expressed as follows:

for (initialization; termination; increment) {
    statement(s)
}

...

The three expressions of the for loop are optional

Means that you could create for loop and leave some of 3 expr empty. One of options is declare int v before loop:

int v = 0;
for(; v<2; v++)

Tags:

Java