Java Blocks




Hey, welcome to the tutorial Blocks. Have you noticed that we have used “}” and “{“ braces very often in writing code?

Now, everything within { and } is collectively called a block.

Eg:

This will be more clear to you with this picture:

So, if a block is started by {, then it definitely should end by writing }.

Try deleting one of } and see you will get an error.

Now can you see how these blocks are positioned relative to each other?

The 1st block is the biggest guy and all the other blocks are started and ended inside it.

Have you noticed the gap between the ending } braces of 1st block and 2nd block?

They have a gap right? Similarly between 2 and 4 endings 4 and 5 endings, we can observe the same. This indentation helps us to understand the parent and child blocks.

This is not a rule. But a convention among programmers to keep things in an order.

3rd block and 4th block are independent of each other. Just like two children in a family. But the 5th block is inside the 4th block. So 5th one is like a child of the 4th block. It’s easy. Isn’t it?

OK. Now let me create a new variable inside the 3rd block.

The 2nd println statement will print the value 234 in the console. But what happens if we try to write the same println statement in the 4th block?? Let’s give a try…

An error occurs. Why?? I have told you that the blocks 3 and 4 are independent of each other. They don’t share a direct connection with each other.

So remember, any variable defined in 3rd block is not visible to the 4th. The integer variable block 3 is called a local variable.

But what happens if you make a new variable in 4th block and print it in 5th block??

The 5th block itself is inside the scope of the 4th block. So any variable declared in 4th block is visible to the child block, 5th.

Those are the important things you have to remember in blocks. Let’s move to our next lesson quickly now…