Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoping rules in Java

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?

like image 781
Matthew Gilliard Avatar asked Apr 22 '26 09:04

Matthew Gilliard


2 Answers

think of for loop actually represented like this:

{
  int i = 0;
  while (i < 10) {
    // your code
    i ++
  }
}
like image 92
iluxa Avatar answered Apr 23 '26 23:04

iluxa


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.

like image 41
OscarRyz Avatar answered Apr 23 '26 23:04

OscarRyz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!