Menu
Topics Index
...
`

Nestedmultiple blocks - Java Example Program


Nestedmultiple blocks
class NestedMultipleBlocks
{
    public static void main(String arg[])
    {
        int x = 10;    // LINE A
        int a = 20;    // LINE B
        
        System.out.println("x = " + x);
        
        {
            // INNER BLOCK 1
            int y = x * 2;
            System.out.println("y in inner block 1 = " + y );
            x = 50;
            System.out.println("x in inner block 1 = " + x );
        }
        // LINE C
        
        // System.out.println("y = " + y); // Won't work
        int z = 20;
        System.out.println("z = " + z);
        
        {
            // INNER BLOCK 2
            int y = x * 3;
            System.out.println("y in inner block 2 = " + y );
            z = y;
            System.out.println("z in inner block 2 = " + z );
        }
        
        // int a = 70;     // Won't work   // LINE D
        
        System.out.println("x after the blocks = " + x);
        
        // System.out.println("y = " + y); // Won't work // LINE E
        
        System.out.println("z after the blocks = " + z); // LINE F
    
    }
}
OUTPUT

x = 10
y in inner block 1 = 20
x in inner block 1 = 50
z = 20
y in inner block 2 = 150
z in inner block 2 = 150
x after the blocks = 50
z after the blocks = 150

DESCRIPTION

Here x is valid in all lines below LINE A, a is valid in all lines below LINE B.
y declared in INNER BLOCK 1 is valid only inside that block and is not valid after LINE C.
y can be declared again in INNER BLOCK 2 and will be valid only in that block.
z declared above INNER BLOCK 2 is valid inside INNER BLOCK 2 as well as after the block i.e. in LINE F.
Redeclaring a again in LINE D will not work since there is already a variable with the same name in the scope.
Trying to print y after INNER BLOCK 1 or INNER BLOCK 2 will not work since the scope is restricted only to inside the blocks.

THINGS TO TRY
  • Uncomment - the statement int a = 70; at LINE D to see the error - "a is already defined in main"
  • Uncomment - the statement System.out.println("y = " + y); at LINE E to see the error - "cannot find symbol"
  • Change int y = x * 3; to y = x * 3; in LINE C1 to see the error - "cannot find symbol"

© meritcampus 2019

All Rights Reserved.

Open In App