Academic Java    Java Tutorial  >  Statements  >  compound statement (block)

compound statement Example

Java compound statement EXAMPLE output Java compound statement EXAMPLE output A compound statement is a group of any number of statements within curly braces.

A compound statement (also called a 'code block' or 'block') is regarded by Java as a statement. This means it can be placed anywhere a statement can be placed.

Variables declared in a block are local to that block. That is, their scope is limited to the block they are declared in, which means they cannot be used outside of that block. The images show the output (the green box is obscured by the black box).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Compound Statement Example
import java.awt.*;

class Staf {

   public static void main(String[] args) {

      int i=22;

      {
         int j, k=5;
         ABox b = new ABox(Color.green);
         b.draw();
      }

      {
         int k=-8;
         System.out.println("k="+k);
         ABox b = new ABox(Color.black);
         b.draw();
      }

      {
         int n = 333;
         {
            System.out.println("n="+n);
            System.out.println("i="+i);
         }
      }

      System.out.println("i="+i);

   }
}

10-14 This is a block.
The variables declared in it, j k and b, cannot be seen outside of the block.

16-21 Another block with some local declarations.
Notice that a reference variable b was also declared in the previous block. However, because the two declarations are local to their respective blocks the compiler will not report a name conflict.

23-29 This code shows a block within a block.
The same rules apply. What's declared in the outer block can be 'seen' by the inner block.
Any variables declared in the inner block cannot be used by an outer block.