Static Block in Java

Static block in Java is used to initialize the static variables (also known as class variables). To initialize instance variables there are constructors, where error handling or other logic can be used. To provide the same capability for class variables, there are static initialization blocks in Java.

Syntax of Java static block

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.

Points about static block in Java

  1. Java static block is executed only once, when the class is first loaded.
  2. Static block is executed before the execution of the main method starts.
  3. Non-static variables can’t be accessed with in a Java static block.
  4. A class can have any number of static initialization blocks, and they can appear anywhere in the class body.
  5. The runtime system guarantees that static initialization blocks are executed in the sequence that they appear in the source code.

Java static block example

Output

Few points to note here are-

1- In the code there are 2 static blocks, both are executed in sequence.
2- From the output you can see that the static blocks are executed before the main method and thus the constructor.
3- Trying to access non-static variable in a static block results in compile-time error.

Exception handling in Java static block

1- You can’t use throws clause with static block so statement like below will result in compile time error.

2- Trying to throw a checked exception from a static block is also not possible. You can have a try-catch block in a static block where checked exception may be thrown from the try block but you will have to resolve it with in catch block. You can’t propagate it further using a throw keyword.

As you can see every time you try to throw a checked exception you will get an error which prompts you to wrap it in a try-catch block.
3- You can throw an unchecked exception from a static block. In case of checked exception too you can wrap it with in an unchecked exception and throw it as shown in code below-

That’s all for the topic Static Block in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.