Java: Initialize multiple variables in for loop init?

The initialization of a for statement follows the rules for local variable declarations.

This would be legal (if silly):

for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) {
  // something
}

But trying to declare the distinct Node and int types as you want is not legal for local variable declarations.

You can limit the scope of additional variables within methods by using a block like this:

{
  int n = 0;
  for (Object o = new Object();/* expr */;/* expr */) {
    // do something
  }
}

This ensures that you don’t accidentally reuse the variable elsewhere in the method.

Leave a Comment