Java allows two or more statements to be grouped into blocks of code also called code blocks.This is done by enclosing the statement between opening and closing curly braces.A block of statement should be a logical statement. It works a particular task. For example, a block can be a target for Java's if and for statement
if ( x < y ) { // Block begins
x = y;
y = 0;
} //Blocks end
Here, if value of x is less than y then we enters the code block for execution. What ever we given in the code block it will execute
Lets look at another example. The following program uses a block of code as the target of a for loop
class BlockTest {
public static void main ( String args [ ] ) {
int x, y;
y = 20;
for ( x = 0; x < 10; x++) {
System.out.println ( " This is X= " +x);
System.out.println ( " This is Y= " +y);
y = y - 2;
}
}
}
if ( x < y ) { // Block begins
x = y;
y = 0;
} //Blocks end
Here, if value of x is less than y then we enters the code block for execution. What ever we given in the code block it will execute
Lets look at another example. The following program uses a block of code as the target of a for loop
class BlockTest {
public static void main ( String args [ ] ) {
int x, y;
y = 20;
for ( x = 0; x < 10; x++) {
System.out.println ( " This is X= " +x);
System.out.println ( " This is Y= " +y);
y = y - 2;
}
}
}
No comments:
Post a Comment