Static Control Flow in Java

JavaServer Side ProgrammingProgramming

The Static Control Flow identify static members, executes static blocks, and then executes the static main method. Let us see an example −

Example

 Live Demo

public class Demo{
   static int a = 97;
   public static void main(String[] args){
      print();
      System.out.println("The main method has completed executing");
   }
   static{
      System.out.println(a);
      print();
      System.out.println("We are inside the first static block");
   }
   public static void print(){
      System.out.println(b);
   }
   static{
      System.out.println("We are inside the second static block");
   }
   static int b = 899;
}

Output

97
0
We are inside the first static block
We are inside the second static block
899
The main method has completed executing

A class named Demo contains a static variable, and a main function, where the ‘print’ function is called. Another static block prints the previously defined static variable and calls the ‘print’ function again. Another static ‘print’ function is defined, that prints another variable. Yet another static block is defined, that prints relevant message. Outside all these static blocks of code, another static integer is defined.

raja
Published on 13-Jul-2020 12:28:59
Advertisements