What is Block Statement 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. In some situations, you can use only one statement. If you want to use more than one statement in those situations, you can create a block statement by placing all your statements inside braces, which would be treated as a single statement. You can think of a block statement as a compound statement that is treated as one statement.

An example of block statement is given below.

{ //block start
        int var = 20;
        var++;
} //block end

Scope of variables

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.

{ //block start
        int var = 20;
        var++;
} //block end
// A compile-time error. var has been declared inside a block and
// so it cannot be used outside that block
Syetem.out.println(var);

Similarily, 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 enclosing outer blocks.

During object creation

Another thing which may interest you that block statements need not to be only inside methods. You can write them as other class members such as class variables and methods.

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");
	}
}
Please note that when block statements are declared in such way, non-static blocks will be executed everytime an instance of class is created. Static block will be execute only once when class is loaded by JVM clas loaders (Much like other static variables present at class level).

That’s all you will need to know about block staments in java. Drop me your questions if any.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.