-2

I always wondered, why doesn't this compile?

for(int i=0, int q=0; i<a.length; i++){
   ...
}

Why doesn't Java allow me to declare more than one variable in the for loop 'header'? Is there a logical reason behind this?

Aviv Cohn
  • 11,431
  • 20
  • 52
  • 95

2 Answers2

6

The semicolon in for delimits three distinct sections each with a completely different purpose (initialization, condition, and action). Adding more semicolons will simply confuse the parser because the parser wouldn't be able to figure out which one means what. Have you tried

for (int i = 0, q = 0; i < a.length; i++)

instead? You are permitted to add as many variables as you'd like, but only of a single type:

for (int i = 0, q = 0, r = 0, ...; i < a.length; i++)

This limitation was likely inherited from C, which has the same behavior.

Rufflewind
  • 7,892
  • 1
  • 32
  • 50
  • Of course, the semicolon was a mistake. I did mean a coma. And yes, I tried it, it doesn't work. Java does allow initializing more than one variable, but only declaring one. – Aviv Cohn Sep 07 '14 at 22:14
  • Are you sure? It works just fine for me (if you remove the second `int`). – Rufflewind Sep 07 '14 at 22:17
2

Because you have already initialized int.

The correct syntax is:

    for (int i = 0, b = 0; i < 5; i++) {
        //....
    }

Same as if you do

private int a,b; or private int a = 55, b = 52;

In Java, you can (and have to) set values with a comma with only declaring the type once.

Object a, b, c, d;

And so on.

Same goes for adding multiple conditions & action:

    for (int i = 0, b = 0; i < 5 && b > 7; i++, b++) {
        // Yay
    } 
Artemkller545
  • 929
  • 3
  • 17
  • 52