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?
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?
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.
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
}