Static block structure changing after compilation

64 Views Asked by At

I'm declaring a static variable after static block. When I'm calling a method to print its value, the result is 0. I decompiled the .class file and found that the structure of the static block has changed. Can anyone please explain why?

class Testing {
static {
    callMe();
    System.out.println("Static finished");
}
static void callMe() {
    System.out.println(x);
}
static int x = 10;
public static void main(String[] args) {
    System.out.println("Complete");
}}

Decompiled code :

class Testing {
static int x;

Testing() {
}

static void callMe() {
    System.out.println(x);
}

public static void main(String[] args) {
    System.out.println("Complete");
}

static {
    callMe();
    System.out.println("Static finished");
    x = 10;
}}
1

There are 1 best solutions below

5
Bohemian On

The compiler is allowed to reorder execution if the overall result is the same.

In your case this is so, because static blocks and initializers are executed in declared order, so the in-line assignment of static int x = 10; is executed after the print.

As for why your exact compiler version reordered your code the way it did is a question for the compiler dev team.