Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What are static blocks in Java?

abhilash

Overview

When the static keyword is attached to a block of code, the block is called a static block.

Syntax

class Main{
   static {
        System.out.println("Hello World");
    }
}

Execution of static blocks

  • Static blocks in Java are executed automatically when the class is loaded in memory.
  • Static blocks are executed before the main() method.
  • Static blocks are executed only once as the class file is loaded to memory.
  • A class can have any number of static initialization blocks.
  • The execution of multiple static blocks will be in the same sequence as written in the program. For example, the static blocks are executed from top to bottom.
  • It’s possible to have only static blocks without a main() method up to Java version 1.5.
  • Static blocks cannot access instance (non-static) variables and methods.

Advantages of static blocks

  1. The logic to be executed during the class loading before executing the main() method can be in a static block.
  2. Static blocks are mainly used to initialize the static variables.

Code

class Main{

    static {
        System.out.println("Static Block 1");
    }

    static {
        System.out.println("Static Block 2");
    }

    public static void main(String[] args) {
        System.out.println("hello world");
    }
}
The execution of a static block using Java

Explanation

  • Lines 3–5: We define a static block that prints Static Block 1.
  • Lines 7–9: We define a static block that prints Static Block 2.
  • Lines 11–13: We define the main method that prints hello world.

When the code is run, first the code in the static block is run then the main method is executed.

RELATED TAGS

java
RELATED COURSES

View all Courses

Keep Exploring