Alex
Alex

Reputation: 891

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.

Upvotes: 4

Views: 1543

Answers (2)

Darth Android
Darth Android

Reputation: 3502

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.

Upvotes: 3

IceFire
IceFire

Reputation: 4138

This does not work in C/C++ either, not sure about C#, though.

The first part of your for statement might have multiple variables, but with the same type. The reason for this is that it is generally not possible to write:

int n = 0, char c = 5;

If you would like to do this, you needed two statements. Similarly, the first part of for only accepts one statement, so that you cannot put two ones in here.

Upvotes: 1

Related Questions