Java Reference
In-Depth Information
statement. You can think of a block statement as a compound statement that is treated as one statement. The
following are examples of block statements:
{ // Start of a block statement. Block statement starts with {
int num1 = 20;
num1++;
} // End of the block statement. Block statement ends with }
{
// Another valid block statement with no statements inside
}
All the variables declared in a block statement can only be used within that block. In other words, you can say
that all variables declared in a block have local scope. Consider the following piece of code:
// Declare a variable num1
int num1;
{ // Start of a block statement
// Declares a variable num2, which is a local variable for this block
int num2;
// num2 is local to this block, so it can be used here
num2 = 200;
// We can use num1 here because it is declared outside and before this block
num1 = 100;
} // End of the block statement
// A compile-time error. num2 has been declared inside a block and
// so it cannot be used outside that block
num2 = 50;
You can also nest a block statement inside another block statement. All the variables declared in the enclosing
blocks (outer blocks) are available to the enclosed blocks (inner blocks). However, the variables declared in the
enclosed inner blocks are not available in enclosing outer blocks. For example,
// Start of the outer block
{
int num1 = 10;
// Start of the inner block
{
// num1 is available here because we are in an inner block
num1 = 100;
int num2 = 200; // Declared inside the inner block
num2 = 678; // OK. num2 is local to inner block
}
// End of the inner block
Search WWH ::




Custom Search