Using Blocks of Code

Java can group two or more statements into blocks of code. Code block is enclosing the statements between opening and closing curly braces({}).

For example, a block can be a target for Java's if and for statements. Consider this if statement:

public class Main {
    public static void main(String args[]) {
        int x, y;
        x = 10;
        y = 20;
        if (x < y) { // begin a block
            x = y;
            y = 0;
            System.out.println("x=" + x);
            System.out.println("y=" + y);
        } // end of block
    }
}

Here is the output of the code above:


x=20
y=0

Use a block of code as the target of a for loop.

public class Main {
  public static void main(String args[]) {
    int i, y;
    y = 20;
    for (i = 0; i < 10; i++) { // the target of this loop is a block
      System.out.println("This is i: " + i);
      System.out.println("This is y: " + y);
      y = y - 1;

    }
  }
}  

The output generated by this program is shown here:


This is i: 0
This is y: 20
This is i: 1
This is y: 19
This is i: 2
This is y: 18
This is i: 3
This is y: 17
This is i: 4
This is y: 16
This is i: 5
This is y: 15
This is i: 6
This is y: 14
This is i: 7
This is y: 13
This is i: 8
This is y: 12
This is i: 9
This is y: 11
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.