Understanding Block Scopes

Understanding Block Scopes

The Easiest Way.

·

1 min read

A block of code is nothing but everything inside the curly braces {}.

Let's directly look at an example :

public static void main(String[] args){
     int a = 10;
     {
      a = 20;
      int b = 30;
     }
}

Here, "a" will be accessible throughout the main function because it is initialised inside it (that is why we are able to update the value of "a" inside another block), but "b", on the other hand, is initialised in a different block of code which makes it inaccessible to anywhere but that block.

This is analogous to if/else statement blocks or the scope of variables inside loops.

As a thumb rule:

Anything initialised outside of the block will be accessible inside it. Anything initialised inside of the block won't be accessible outside it.

You can even initialise "b" again outside of its block and the code will be error-free.

 int a = 10;
     {
      a = 20;
      int b = 30;
     }
int b = 25;

I just learnt this and wanted to share. ~(˘▾˘~)