0

As i read every one is saying static block will be executed first but when i run a piece of code i found that static variable is loading first.Now this is confusing me please give a proper explanation.

Code

public class MyClass 
{
    static int x=show();
    static
    {
        System.out.println("Hello Mayar");
    }
    public static int show()
    {
        System.out.println("Hello Show");
        return 1;
    }
    public static void main(String a[])
    {
        System.out.println("Hello Main");
    }
}

Output

Hello Show
Hello Mayar
Hello Main
baao
  • 71,625
  • 17
  • 143
  • 203

1 Answers1

7

Static blocks and variables are evaluated in their order of appearance within the java source file.

As per Java 8 spec on class initialization:

  1. Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
diginoise
  • 7,352
  • 2
  • 31
  • 39