Static Control flow
MrJazsohanisharma

Static Control flow

 

Static control flow-:  When ever we are executing a Java class, the following sequence of steps or activity will be executed as the part of static control flow.

  1. Identification of static member from top to bottom
  2. Execution of static variable assignment and static block from top to bottom
  3. Execution of main method.
eg-:
class StaticFlow{
    static int i=10;
    static {
          m1();
          System.out.print("first static block");
    }
    public static void main(String... args){
         m1();
        System.out.print("main method");
    }
    public static void m1(){
       System.out.print(j);
    }
    static int j=20;
}

Note-:

   Direct Read-: Inside a static block read a variable, the read operation called direct read.

   Indirect Read-: If we are calling a method and within that method trying to read a variable, that read operation call indirect read.

eg-:
class DirectReadIndirectRead{
    static int i=10;
    static{
      m1();                        // indirect Read
      System.out.print(i);//direct Read
    }
    public static void m1(){
      System.out.print(i);
    }
}

if a variable is just identify by the JVM and original value not yet assign, then the variable is said to be in read indirectly and write only state(RIWO)

if a variable is and read indirect write only state then we can not perform direct read but we can perform indirect read.

if we are trying to read directly then we will get compile time error illegal forward reference

eg-:

1-: 
class ReadStaticBlockAndVariables{
   static int x=10;
   static{
     System.out.print(x);
   }
}

output-: 10
     RE-:  NoSuchMethodError : main

2-:
class ReadStaticBlockAndVariables{
   static{
     System.out.print(x);
   }
static int x=10;
}

error: illegal forward reference

3-:
class ReadStaticBlockAndVariables{
  static{
    m1();
  }
   public static void m1(){
      System.out.print(x);
   }
  static int x=10;
}
output-: 0
     RE-:  NoSuchMethodError : main



Static Block-:

Static block will executed at the time of class loading, hence at time of class loading if we want to perform any activity we have to define that inside static block.

eg 1-:

At the time of Java class loading the corresponding native library should be loaded, hence we have to define this activity inside static block.

class StaticBlock{
  static{
        System.loadLibrary("native library path");
  }
}

eg 2-:

After loading every database driver class we have to register driver class with driver manager but inside database driver class there is a static block to perform this activity, and we are not responsible to register explicitly

class DBdriver{
   static {
          register this driver with driverManager
  }
}

Note-:
          Within a class any no. of static block but all these static block will executed from top to bottom.


Ques-: Without writhing main method is it possible to print some statements to the console?
Ans-:  yes, by using static block.
   eg-:
       class PrintWithoutMainMethod{
          static {
                    System.out.print("Hello I can print");
                    System.exit(0);
            }
       }
Ques-:Without writhing main method is it possible to print some statements to the console?
Ans -: yes, there are multiple ways.

eg 1-:
 
class Test{
     static int x=m1();
    public static int m1(){
              System.out.print("Hello I can print");
              System.exit(0);
              return 10;
    }
}

eg 2-:

class Test{
     static Test t=new Test();
   {
              System.out.print("Hello I can print");
              System.exit(0);
    }
}

eg 3-:

class Test{
     static Test t=new Test();
    Test() {
              System.out.print("Hello I can print");
               System.exit(0);
    }
}

Note-:
 From 1.7v onward main method is mandatory to start a program execution, hence from 1.7v onward without writing it is impossible to print some statement to the console.


Static control flow in parent to child relationship


When ever executing a child class, the following sequence of even will be executed automatically as a part of static control flow.

  • Identification of static member from parent to child.[1 to 11]
  • Execution of static variable of assignment and static blocks from parent to child. [12 to 22]
  • Execution only child class main method.[23 to 25]
eg-: coloured number denote the execution flow.
 
class Base{
 1 static int i=10; 12
 2  static{
     m1();   13
     System.out.print("Base Static block");  15
 }
3 public static void main(String[] args){
      m1();
      System.out.print("Main method of Base Class");
  }
  public static void m1(){
       System.out.print(j); 14
   }
  static int j=20;  16
}

class Derived extends Base{
6  static int x=20;  17
7  static {
            m1();  18
            System.out.print("Derived First static block");  20
  }
8  public static void main(String[] args){
      m1(); 23
      System.out.print("Derived main");  25
  }
9  public static void m1(){
      System.out.print(y); 19  24
  }
10  static {
     System.out.print("Derived second static Block");  21
  }
11  static int y=200; 22
}

output -:
  javac Derived.java
    0
    Base static block
    0
    Derived First static block
    Derived Second static block
    200
    Derived Main
javac Base.java
    0
    Base static block
    20
    Main method of Base class


This Java code defines two classes, `Base` and `Derived`, and demonstrates the behaviour of static blocks and variables in inheritance. Let's go through each part of the code step by step:


class Base {
    static int i = 10; // Static variable 'i' is declared and initialized to 10.
    static {
        m1(); // Calls the static method 'm1' (defined later in the class).
        System.out.print("Base Static block"); // Prints a message.
    }

    public static void main(String[] args) {
        m1(); // Calls the static method 'm1' again.
        System.out.print("Main method of Base Class"); // Prints a message.
    }

    public static void m1() {
        System.out.print(j); // Prints the value of 'j' (defined later in the class).
    }

    static int j = 20; // Static variable 'j' is declared and initialized to 20.
}


Explanation of `Base` class:
- It has a static variable `i` initialized to 10.
- There's a static initialization block that calls the method `m1()` and prints "Base Static block".
- In the `main` method, it calls `m1()` again and prints "Main method of Base Class".
- There's a static method `m1()` that prints the value of `j`.
- Static variable `j` is declared and initialized to 20.

Now, let's move on to the `Derived` class:


class Derived extends Base {
    static int x = 20; // Static variable 'x' is declared and initialized to 20.
    static {
        m1(); // Calls the overridden static method 'm1' from the 'Derived' class.
        System.out.print("Derived First static block"); // Prints a message.
    }

    public static void main(String[] args) {
        m1(); // Calls the overridden static method 'm1' from the 'Derived' class.
        System.out.print("Derived main"); // Prints a message.
    }

    public static void m1() {
        System.out.print(y); // Prints the value of 'y' (defined later in the 'Derived' class).
    }

    static {
        System.out.print("Derived second static Block"); // Prints a message.
    }

    static int y = 200; // Static variable 'y' is declared and initialized to 200.
}


Explanation of `Derived` class:
- It extends the `Base` class.
- It has a static variable `x` initialized to 20.
- There's a static initialization block that calls the overridden static method `m1()` from the `Derived` class and prints "Derived First static block".
- In the `main` method, it calls the overridden static method `m1()` from the `Derived` class and prints "Derived main".
- There's an overridden static method `m1()` in the `Derived` class that prints the value of `y`.
- There's another static initialization block that prints "Derived second static Block".
- Static variable `y` is declared and initialized to 200.

When you run this program, the static blocks and methods will be executed in a specific order, and messages and variable values will be printed accordingly, demonstrating the behaviour of static elements and inheritance in Java.

Note-: 

Whenever we are loading child class, automatically parent class will be loaded but when ever we are loading parent class child class won't be loaded. Because parent class members by default available to child class where as child class members by default won't to the parent class.