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.
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; }
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!