next up previous
Next: Use of blocks in Up: Unit 05 Previous: Block of statements

Scope of variables defined in a block

A block of statements can contain variable declarations. The scope of a variable declared inside a block is the block itself, including other blocks contained in it, if present. This means that the variable is visible in the block and in all sub-blocks, but is not visible outside the block.

Example:

public class ScopeInBlock {

  public static void main(String[] args) {
    String a = "Hello";
    int i = 1;
    {
      System.out.println(a);
           // OK. a is visible - prints Hello
      //int i;
           // ERROR. i is visibile and cannot be redeclared

      {
        double r = 5.5;          // OK
        i = i + 1;               // OK. i is still visible
        System.out.println(r);   // OK. r is visible - prints 5.5
      }

      //System.out.println(r); // ERROR. r is not visible
      System.out.println(i);   // OK. i is visibile - prints 2

      {
        int r = 4;       // OK. previous r is not visible anymore
        System.out.println(a);
                         // OK. a is still visibile - prints Hello
      }
    }

   i = i + 1;                  // OK. i is visible
   System.out.println(i);      // OK. i is visible - prints 3

  }
}


next up previous
Next: Use of blocks in Up: Unit 05 Previous: Block of statements