Wednesday, February 25, 2015

Blocks of Code

Java allows two or more statements to be grouped into blocks of code, also called code blocks. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be a target for Java’s if and for statements.
Consider this if statement:

if(x < y) { // begin a block
x = y;
y = 0;
} // end of block

Here, if x is less than y, then both statements inside the block will be executed.

Let’s look at another example. The following program uses a block of code as the target
of a for loop.

/*
Demonstrate a block of code.
Call this file "BlockTest.java"
*/
class BlockTest {
      public static void main(String args[]) {
               int x, y;
               y = 20;
// the target of this loop is a block

               for(x = 0; x<10; x++) {
                        System.out.println("This is x: " + x);
                        System.out.println("This is y: " + y);
                        y = y - 2;
                }
        }
}

The output generated by this program is shown here:
This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9

This is y: 2

In this case, the target of the for loop is a block of code and not just a single statement.

0 comments:

Post a Comment