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?
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With