What are the steps to read static members in a Java class?


A static variable gets created at the time of class loading even before the execution of a static block and the purpose of the static block is to assign value to the static variables. A static variable stores a value that is shared between all instances of the class it is defined in and a static block is a section of code that gets executed when class is first loaded.

If we want any logic that needs to be executed at the time of class loading that logic needs to place inside the static block so that it will be executed at the time of class loading.

JVM follows below steps to read static members in a class::

  • Identification of static members from top to bottom.

  • Execution of static variables assignment and static blocks from top to bottom.

  • Execution of the main method.

Example

public class StaticFlow {
   static int firstNumber = 10;
   static {
      firstMethod();
      System.out.println("first static block");
   }
   public static void main(String[] args) {
      firstMethod();
      System.out.println("main method executed");
   }
   public static void firstMethod() {
      System.out.println(secondNumber);
   }
   static {
      System.out.println("second static block");
   }
      static int secondNumber = 20;
}

Output

0
first static block
second static block
20
main method executed

raja
raja

e

Updated on: 22-Nov-2023

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements