Friday, March 25, 2022

Static Blocks in Java


  • Static blocks executed only once when the class is loaded into the memory for the first time.

    public class Main {
      {
          System.out.println("inside instance block");
      }
    
      static {
          System.out.println("inside static block");
      }
    
      public static void main(String[] args) {
          new Main();
          new Main();
          System.out.println("Main Program ");
      }
    }
    //output
    inside static block
    inside instance block
    inside instance block
    Main Program
    
  • A static block will be executed even if there is no main method, for example we print something on the console without creating main() method.
    class Main {
      static {
          System.out.print("Static block without main method");
      }
    }
    //output (works only if JDK version is 1.6 or previous)
    Static block without main method
    
  • Static blocks gets executed before the constructor
  • Static blocks are used for the initialization of static variables
  • A class can have any number of static blocks, and they can appear anywhere in the class body.
  • If there are multiple static blocks then those will be executed from top to bottom.

 

No comments:

Post a Comment