Home » Java » java – Why must a variable be declared in a for loop initialization?-Exceptionshub

java – Why must a variable be declared in a for loop initialization?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:
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?

How to&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;.

Answer:

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.

Answer:

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++)

Answer:

You don’t have to declare a variable in the ForInit.

As others have pointed out, you can simply omit the ForInit; but you can also use a list of statement expressions there.

For example, you can create new class instances, invoke methods and assign/increment/decrement variables:

int v;
for (new String(), "".toString(), v = 0, v++;;);

(This example is nonsensical, but legal)

However, you cannot mix these statement expressions with local variable declarations.

Answer:

You do not need it for an enhanced for loop.

public class Main {
    public static void main(String[] args) {
        int[] integers = { 10, 20, 30 };
        for (int x : integers) {
            System.out.println(x);
        }
    }
}

Answer:

int w =0;

int v;

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

}
you have declared v prior the loop but you again used without any initialization.

if you use w which is already declared and initialized prior then there will be no issues.like below code,

for(;w<2;w++){

}