Java execution priority

Whenever JVM loads the class, it will execute in specific order.

  1. Class variable.
  2. Static blocks
  3. public static void main(String args[])

In the above order JVM execute the program.
First it will looks for Class variables.|

static int value =90;
static String helloString ="Hello";

Then static blocksThis blocks will execute top to bottom.

static{
 System.out.println("Static block-1");
}
static{
 System.out.println("Static block-2");
}

Finally, main method will execute.

So far so good!
Then can we execute java program with out main method?


Yes we can execute if your using the jdk version 1.6 or below.
The later version main method is must.



Eg:
public class MleClass{
 static int valueOne=10;
static {
System.out.println(valueTwo);
}

public static void main(String arg[]){
 System.out.println("Main method");
}
static {
System.out.println(valueOne);
}
 static int valueTwo=20;


Output:
20
10
main method

Note: static block can be used to initialize the static final variables.

Eg:
Valid
public class MleClass{
  static final int finalValue;

 static{
  finalValue= 10
 }
}

Where do we use static blocks in client project ?

- To load the class dependencies.

Eg:

class MleClass{
  static Object init(){
   // Assume here we have some complex logic.
  }
 }

public class MleClass2{

static{
 // To create this class object if we need MleClass class initialization.
  MleClass.init();
 }

}

No comments:

Post a Comment