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

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.


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;.

Tags:

Java