Search code examples
javasyntaxbraces

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?


Solution

  • think of for loop actually represented like this:

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