Tuesday 5 May 2015

Java- static control flow in a class

In this article, we will see what will happen when a class loads into JVM on static members.

JVM follows below steps to read static members in a class.

1. Identification of static members form top to bottom.
2. Execution of static variables assignment and static blocks from top to bottom.
3.Execution of main method.



Test.java

package in.blogspot.java2bigdata;

public class Test{
 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;
}

Output:

0
first static block
second static block
20
main Method executed....
I know the above program is bit confusing, I will try to elaborate more
At first all static members of the class are identified (just identified , no assignment of variables and
execution of static blocks is done), observe [1] to [6] .
After identification variable assignment and execution of static blocks starts from top to bottom so 
value 10 is assigned to int firstNumber[7] , the next static block is executed here firstMethod() 
method is called , observe firstMethod() is trying to print secondNumber which is not yet initialized
so the default value “0” is printed, 
now control flows back to static block and the next statement “First Static Block”[10] is displayed on 
console. After it the second static block is executed and “Second Static Block” is printed[11], now the
secondNumber is initialized[12]. Next the main method is executed [13] to [15].
The static keyword can be used in 3 scenarios:

    static variables
    static methods
    static blocks of code.


I will update static keyword usage in my upcoming post......

If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

2 comments:

  1. excellent post keep up the good work and continue blogging Surya Informatics

    ReplyDelete
  2. This is really a nice and informative, containing all information and also has a great impact on the new technology. Thanks for sharing it,
    代写cs 北美

    ReplyDelete