Static Control Flow - rahul00773/JavaConcepts GitHub Wiki

Whenever we are executing a java class the following sequence of steps will be executed As part of static control flow.

1. Identification of static members from top to bottom. [1-6]
2. Execution of static variables assignment and static blocks from Top to Bottom. [7-12]
3. Execution of the main Method [13-15]

static int x=10;     //1 int x=0 //7 

static{ //2
m1(); // 8
System.out.println(“First Static Block”);  10

}

public static void main(String[] args){ //3
m1(); // 13

System.out.println(“Main Method”);

}

public static void m1(){ 4 //14

System.out.println(j);//  / j=0 //9 
}

static{ //5 
System.out.println(“Second Static Block”); //11
}


static int j =20; //6  // 12 j =20 //
}```



OutPut:/

* 0
* First Static Block
* Second Static Block
* 20
* Main Method



## Read Indirectly Write Only:

Inside a static block if we are trying to read a variable that read operation is called direct read. 
If we are calling a method and within that method if we are trying to read a variable that read operation is called indirect read. 

```class Test{

static int I =10;

static{

m1();

System.out.println(I); // Direct Read
}

public static void m1(){
System.out.println(I); // Indirect read
}

}```


If a variable is just identified by the JVM and original value not yet assigned. Then the variable is set to in read Indirectly and Write only state(RIWO).
If a variable is in Read indirectly write-only state Then we can’t perform direct read. But we can perform Indirect read.

If we are trying to read directly then we will get compile-time error saying “Illegal Forward reference”






Examples:

```class Test{
static int x=10;

static{

System.out.println(x);   // Direct Read
}

}```

// Output would be 10 and error will  come for main method : No such method error main


```class Test{

static{

System.out.println(x);   // Direct Read
}

static int x=10;


}```

// Compile Time error will come “Illegal Forward reference”


```class Test{

static{

m1();
}
public static void m1(){

System.out.println(x);   // Direct Read
}

static int x=10;


}```

// Output would be 0  and error will  come for main method : No such method error main