Scoping rules in Java

2020-03-30 01:58发布

问题:

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?

回答1:

think of for loop actually represented like this:

{
  int i = 0;
  while (i < 10) {
    // your code
    i ++
  }
}


回答2:

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:

  • Scope of a Declaration
  • Scope of Local Variable Declarations

From the language specification.



回答3:

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