In a Java program, suppose there is a static block, a static method and a static variable, during load of JVM, which will be loaded first into the memory and why?
Answered
In a Java program, suppose there is a static block, a static method and a static variable, during load of JVM, which will be loaded first into the memory and why?
Best answer
Let us take the below example for the discussion. In this class, there is a static block, followed by a static method and a static variable.
public class Test { static{ System.out.println(Test.x); } public static void main(String[] args) { System.out.println("Value of x: "+Test.x); } static int x=100; }
The output of this example will be
0
Value of x: 100
In this case, first the static block is invoked because it appears first, next the static variable is initialized and the static method is invoked. The reason is that the static members are initialized in the order in which they appear in the source.
If you change the order as below:
public class Test { public static void main(String[] args) { System.out.println("Value of x: " + Test.x); } static int x = 100; static { System.out.println(Test.x); } }
The output will be
100
Value of x: 100