Menu
Topics Index
...
`

Block of code - Java Example Program


Block of code
class CodeBlock
{
    public static void main(String arg[])
    {
        System.out.println("In main block");
        
        {    // LINE A
            System.out.print("In ");
            System.out.print("inner ");
            System.out.print("block ");    // LINE A1
            System.out.println("One");
        }
        
        {    // LINE B
            System.out.print("In ");
            System.out.print("inner ");
            System.out.print("block ");
            System.out.println("Two");
        
            {    // LINE C
                System.out.println ("Block inside inner block two");
            }
        } // LINE D    
    }
}
OUTPUT

In main block
In inner block One
In inner block Two
Block inside inner block two

DESCRIPTION

Here we have two inner blocks starting at LINE A and LINE B. Inside the second inner block we have one more block starting at LINE C. The class content and the main method content are also blocks. In total there are 5 blocks in this program.

THINGS TO TRY
  • Remove the open curly brace at LINE C and check what compilation error do you get.
  • Remove the close curly brace at LINE D and see the compilation error. Is the error same as what we got when we removed the open brace.
  • Change the code to remove all the curly braces for the three blocks and check if the output changes.
  • Include LINE A1 inside one more block and see the output.

© meritcampus 2019

All Rights Reserved.

Open In App