print
Advertisment
Advertisment

Static Control Flow in java

Static control flow is used to decide the sequence of activities that will be executed in order when we run a java class that contains static variables, blocks, and methods. Static control flow is performed in these 3 steps in an exact way.


  1. It identifies all the static members as variables, blocks, and methods from top to bottom
  2. It executes the static variable assignment and the static block from top to bottom.
  3. And in last the static main method is executed.

Static Control Flow example in java

class StaticControlFlow{
   static int i = 80;

   public static void main(String[] args) {
       print();
       System.out.println("main method execution finished");
   }
//static block 1
   static {
       System.out.println(i);
       print();
       System.out.println("first static block");
   }

   public static void print(){
       System.out.println(j);
   }
//static block 2
   static {
       System.out.println("second static block");
   }
   static int j = 89;
}

Output :

 
  
 80
 0
 first static block
 second static block
 89
 main method execution finished
 
 Process finished with exit code 0
  

Static Control Flow working mechanism

When we will execute the above program, the mechanism of static control flow will execute the three-step process that has been told above. In the first step, it will identify all the static members from top to bottom. And because the variable i has been initialized before execution of the first static block so its value is 80. But because j is not initialized yet so its value will be the default value of int which is 0. And in the last step the static main method is executed till then all the static members have been identified so all the values have been assigned then in the main method static print() method is called again and this time the value of j is printed as its value 89.

Static Control Flow example in java

Finally, the constructor is executed in the last step of the static control flow if the constructor is created in the static control flow.

class Static{
      static int a = 10;   
      static {
            System.out.println("static initializing block");
            }
public static void run(){
               System.out.println("static method");  
            }
       Static(){
             System.out.println("constructor");  
	        }
public static void main(String[] args) {
	   System.out.println(a);
       System.out.println("main method execution");
       Static s = new Static();
	 }
   }

Output :

 
 
 static initializing block
 10
 main method execution
 constructor

Advertisment
Advertisment
arrow_upward