Site icon TestingDocs.com

Java Static Block

Overview

A static block in Java is executed when the class loads and before the main method is executed. Let’s see the functioning of the static block in the below java program and understand the importance of the static block in Java. We can use this block as an initialization block in the automation code.

Java Program

package com.testingdocs.tutorial.staticpkg;

//StaticBloclDemo.java
//www.TestingDocs.com
public class StaticBlockDemo {
  static int count =0;
  static {
    //This will execute before the main.
    System.out.println("The static block is executed.");	 	 
  }

  public static void main(String[] args) {	 	 
    System.out.println("In Main method.");	 	 
  }	 	 

}

 

Program Output

The static block is executed.
In Main method.

 

Java class can have multiple static blocks.All the blocks would be executed first.

package com.testingdocs.tutorial.staticpkg;

//StaticBloclDemo.java
//www.TestingDocs.com
public class StaticBlockDemo {
  static int count =0;
  static {
    //static block 1.
    System.out.println("The static block 1.");	 	 
  }

  public static void main(String[] args) {	 	 
    System.out.println("In Main method.");	 	 
  }
  
  static {
    //static block 2.
    System.out.println("The static block 2.");	 	 
  }

}

The static block 1.
The static block 2.
In Main method.

 

Exit mobile version