4.1.3.1 Compound Statement


You can collect several Java statements into one statement by bracketing it with curly brackets into a compound statement or program block. The scope of variable declared inside a program block is restricted to this program section and its subsections. However, it is not possible to declare identically named variables in two different blocks in the same method that exist at the same time.

The following small Java application shows blocks of statements. The variables t are all refering to different objects. After the last declaration and initialization of the variables t it cannot be introduced anew in the main method. The variable r exists and can be used at every location in the main method.

public class blockTest {
  public static void main(String[] args) {
    int r;     // declaration of integer r
    { int t=2; // introduction of temporary integer t
      r = 3*t;
      System.out.println("t = "+t+", 3*t = "+r);
    };
    { int t=4; // introduction of new temporary integer t
      r = 5*t; 
      System.out.println("t = " + t + ", 5*t = " + r);
    };
    int t = 6; // introduction of integer t in the
               // rest of the main method
    r = 7*t;
    System.out.println("t = " + t + ", 5*t = " + r);
  }
}
When you run this program you will see on your computer screen.
t = 2, 3*t = 6
t = 4, 5*t = 20
t = 6, 7*t = 42