Static blocks in Java with example

The static block executes when classloader loads the class. A static block is invoked before main() method. Let us see an example −


 Live Demo

class Demo{
   static int val_1;
   int val_2;
      val_1 = 67;
      System.out.println("The static block has been called.");
public class Main{
   public static void main(String args[]){


The static block has been called.

A class named Demo contains a static integer value and a normal integer value. In a static block, a value is defined, and in the main class, an instance of the Demo class is created and the static integer is accessed from there.

Updated on: 13-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started