0

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;
}}
  • Does this answer your question? [in what order are static blocks and static variables in a class executed?](https://stackoverflow.com/questions/12448465/in-what-order-are-static-blocks-and-static-variables-in-a-class-executed) – akuzminykh Aug 29 '20 at 20:59

1 Answers1

1

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • I have assigned 10 to x, shouldn't that be printed? – Abhishek Sahu Aug 29 '20 at 21:00
  • No - static stuff is executed in declared order, so the assigning the value of 10 happens *after* the print. See edited answer. – Bohemian Aug 29 '20 at 21:03
  • Yeah, that is fine when I see the decompiled code. But why my expression broke into two parts and initialization shifted into static method? – Abhishek Sahu Aug 29 '20 at 21:09
  • Like I said, the compiler can rearrange the code as it likes. There is probably some micro optimisation reason. – Bohemian Aug 29 '20 at 21:11
  • 1
    There is neither reordering nor optimization going on. There is only one static block in the compiled class file. The decompiler simply doesn’t know that this code was spread over different parts in the original source code. – Holger Aug 31 '20 at 07:25