Block of code in Java allows grouping of two or more statements. We use curly braces { } to denote a block of code in Java. Block of code in Java can be used where ever we use a statement.

Every block of code in Java starts with a open curly brace { and ends with close curly brace }.

There is no restriction on the number of blocks inside a block and the level of nesting the blocks. i.e. Blocks can be nested and can be included inside other blocks.

Block of code in Java is commonly used in if, for and while statements.

All class and method contents are also blocks e.g., the class content or the main method in the examples are blocks.

It is advised to indent i.e. put tabs or spaces so that the inside blocks are one tab more than the containing block. Indenting the blocks will help in resolving the compilation errors faster and the programs will be easy to read.

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.

Here we want to print Excellent and Scholarship granted when marks are greater than 90. If we do not include these two statements in the code block i.e. in curly braces { }, then Scholarship granted will be printed whether or not marks are greater than 90. Since if considers only the first statement after the condition. Even indenting will not help, since java is free-form language and does not give importance to spaces, tabs etc.

THINGS TO TRY

Remove curly braces enclosing LINE A and LINE B and compile it. Change marks to 100, 90 and 80 and see the various outputs.

Include LINE B inside one more block i.e. place open curly brace { just before System in LINE B and close curly brace } just after ; and before comment // LINE B. If it is placed after // LINE B it will be considered as a comment and throws a compilation error.