4

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.

1
  • can u ever define int i =0 ,char c ='a';?, don't think it works in c++ or c# Commented Mar 16, 2016 at 15:11

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.