2

Can someone help me understand the scoping rules in Java? This is clearly not valid:

    {
        int i = 0;
        System.out.println(i); // fine, of course
    }
    System.out.println(i); // syntax error

i is declared within the {}, and it's not available outside. So what about this:

    for (int i = 0; i < 10; i++) {
         System.out.println(i); // fine, of course
    }
    System.out.println(i);  // syntax error, same as above.

I'm surprised at the syntax error here. i is declared in the outer scope yet it is not available later on. Is it bound to the inner block scope by some special rule for for loops? Are there other scenarios where this can happen?

Matthew Gilliard
  • 8,783
  • 3
  • 28
  • 47
  • 2
    There is a difference between the "bare" `{}` and `{}` associated with *any other keywords or grammar production* -- that is, it must be viewed in the context of the grammar even if a number of cases have similar semantics. –  Mar 04 '11 at 22:16

3 Answers3

6

think of for loop actually represented like this:

{
  int i = 0;
  while (i < 10) {
    // your code
    i ++
  }
}
iluxa
  • 6,733
  • 16
  • 33
  • 1
    Yes, this is supported by the JLS (http://java.sun.com/docs/books/jls/third_edition/html/statements.html#35529) "If the ForInit code is a local variable declaration, it is executed as if it were a local variable declaration statement appearing in a block. " – Matthew Gilliard Mar 04 '11 at 22:46
3

Is it bound to the inner block scope by some special rule for for loops?

Yes, this is exactly the case.

There's obviously the local variable declaration:

class Some { 
   public void x( int i ) { 
    System.out.println( i ); // valid 
   }
   int j = i; // not valid 
}

See also:

From the language specification.

OscarRyz
  • 184,433
  • 106
  • 369
  • 548
0

It's the defined behavior of the for loop in Java.

class ForDemo {
     public static void main(String[] args){
          for(int i=1; i<11; i++){
               System.out.println("Count is: " + i);
          }
     }
}

Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.

Source: http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html

rkg
  • 5,173
  • 7
  • 32
  • 47