Blocks in Java – Computer Sir Ki Class


Code Learning #JAVA#3770 siteicon   siteicon   siteicon  

Blocks in Java

Demonstration of use of blocks in java.

Learning Objectives

  • Understanding the block and its scope restrictions.

Source Code

TC++ #3770

Source Code

Run Output

a+b = 3

Code Understanding

Note: every pair of curly braces is mark a set of instructions, functions etc. to mark a scope of content usage which is called a block.
class Blocks

{  //This is class level block code begin
public static void main(String[] args)
{ //This is main function level block
boolean x=true;  //Here a boolean variable x has been defined.
//int a=0,b=0;        //This code may be used if variables are not declared inside block

if(x) //This is a control flow statement which will need blocks.
{        //For multiple instructions in a control flow condition block is required.
int a=1;
int b=2;
These two variables are declared inside the control flow block
System.out.println(“a+b = “+(a+b));
This instruction uses variable declared inside the block so it has to be inside the block only.
//System.out.println(“a+b = “+(a+b));
This instruction will fail if variables are declared inside the block. To make this instruction work, one must declare variables inside the main function block and outside the flow control block.


  • Unlike some other languages, Java doesn’t allow re-declaration of variables in the nested blocks within a function. For e.g.
    int a=10;
    for(int a=10;a<20;a++) ;
    will not be permitted. int a inside the for loop will be considered a re-declaration.

Suggested Filename(s):


sunmitra| Created: 5-Mar-2018 | Updated: 5-Mar-2018|