Home  >  Article  >  Java  >  What are the steps to read static members in Java class?

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

WBOY
WBOYforward
2023-08-30 20:41:101029browse

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

Static variables are created when the class is loaded or even before the static block is executed. The purpose of the static block is to assign values ​​to static variables. A static variable stores a value that is shared among all instances of the class in which it is defined, and a static block is a section of code that is executed when a class is first loaded. If we want to execute any logic on class loading, then that logic needs to be placed inside a static block to be executed on class loading.

JVM follows the following steps to execute reading static members in a class::

  • Identify static members from top to bottom
  • Execute static variables from top to bottom Assignment and static blocks.
  • Execution of 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

The above is the detailed content of What are the steps to read static members in Java class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete