Block Statements in Java

A block statement is a sequence of zero or more statements enclosed in braces. A block statement is generally used to group together several statements, so they can be used in a situation that requires you to use a single statement.

1. What is a Block Statement?

Generally, a java program is a combination of single statements that should be executed sequentially. In some cases, if we want to use more than one statement to represent a unit of work, we can create a block statement by placing all related statements inside braces, which would be treated as a single statement. You can think of a block statement as a compound statement treated as one.

An example of a block statement is given below.

{ 
        int var = 20;
        var++;
} 

2. Scope of Variables inside Blocks?

Please note that all the variables declared in a block statement can only be used within that block. In other words, you can say that all variables declared in a block have local scope.

{ 
        int var = 20;
        var++;
} 

// A compile-time error. var has been declared inside a block and
// so it cannot be used outside that block
Syetem.out.println(var);

Similarly, you can also nest a block statement inside another block statement. All the variables declared in the enclosing blocks (outer blocks) are available to the enclosed blocks (inner blocks). However, the variables declared in the enclosed inner blocks are not available in the enclosed outer blocks.

3. Blocks during object creation

Another thing that may interest you is that block statements need not be only inside methods. You can write them to write object initialization logic.

Please note that when block statements are declared in such a way, non-static blocks will be executed every time an instance of the class is created. The static blocks will be executed only once when the class is loaded by JVM class loaders (Much like other static variables present at the class level).

public class MyDemoAction
{
	private Interger variable = 10;

	public MyDemoAction(){
		System.out.println("MyDemoAction Constructor");
	}

	{
		//Non-static block statement
	}

	static {
		//Static block statement
	}

	private void someMethod() {
		System.out.println("HowToDoInJava.com");
	}
}

That’s all you will need to know about block statements in java.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode