Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring different type variables inside for condition in Java

Is it possible to declare two variables of different types in initialization of for statement in Java?

for (char letter = 'a', int num = 1; maxLine - num > 0; letter++, num++) {
    System.out.print(letter);
}

Coming from C/C#, I tried to do it as above, but the compiler says it expects a semicolon identifier after the letter variable declaration.

like image 477
Alex Avatar asked Sep 19 '25 02:09

Alex


1 Answers

Because the variable declaration in a for loop follows that of local variable declaration.

Similar to how the following is not valid as a local declaration because it contains multiple types:

char letter = 'a', int num = 1;

It is also not valid in a for loop. You can, however, define multiple variables of the same type:

for (int n = 0, m = 5; n*m < 400; n++) {}

As to why the designers made it that way, ask them if you see them.

like image 105
Darth Android Avatar answered Sep 20 '25 16:09

Darth Android