Java - Statement Block Statement

What is Block Statement?

A block statement is a sequence of zero or more statements enclosed in braces.

A block statement groups several statements which is treated as one statement.

The following are examples of block statements:

Block statement starts with { and ends with }

{
        int num1 = 20;
        num1++;
}

Variable Block Scope

Variables declared in a block statement can only be used within that block.

All variables declared in a block have local scope.

In the following code, num2 is declared inside a block and cannot be used outside that block.

int num1;

{
   int num2;
   num2 = 200;
   num1 = 100;
}
num2 = 50; // A compile-time error. 

Nested Block

You can nest a block statement inside another block statement.

All the variables declared in the outer blocks are available to the inner blocks.

The variables declared in the inner blocks are not available in outer blocks. For example,

//outer block
{
        int num1 = 10;
        // inner block
        {
                // num1 is available here because we are in an inner block
                num1 = 100;
                int num2 = 200; // Declared inside the inner block
                num2 = 100;     // OK. num2 is local to inner block
        }
        // End of the inner block
        num2 = 200; // A compile-time error. 
}
// End of the outer block

The inner block cannot defines a variable with the same name as the outer scope.

int num1 = 10;
{
        float num1 = 1.5F; // A compile-time error. num1 is already in scope.
        float num2 = 1.98F; // OK
        {
                float num2;// A compile-time error. num2 is already in scope.
        }
}

Related Topics

Quiz