Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

int v = 0;

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

}

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization? I know it's not a statement if I do it like that but why doesn't Java allow the above?

like image 682
mightyandweakcoder Avatar asked Feb 17 '20 14:02

mightyandweakcoder


2 Answers

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

like image 127
Eran Avatar answered Nov 11 '22 13:11

Eran


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.

like image 36
Nexevis Avatar answered Nov 11 '22 13:11

Nexevis