Java classes and static blocks

2019-03-22 15:27发布

class Hello12 {
    static int b = 10;
    static {
        b = 100;
    }
}

class sample {
    public static void main(String args[]) {
        System.out.println(Hello12.b);
    }
}

On running above code the output comes as 100 because when I called Hello class, static block is executed first setting the value of b to 100 and displaying it. But when i write this code:

class Hello12 {
    static {
         b = 100;
    }
    static int b = 10;
}

class sample {
    public static void main(String args[]) {
        System.out.println(Hello12.b);
    }
}

Here the output comes as 10. I am expecting answer as 100 because once the static block is executed it gave b the value as 100. so when in main(), I called Hello.b it should have referred to b (=100). How is the memory allocated to b in both the codes?

标签: java static
4条回答
做自己的国王
2楼-- · 2019-03-22 15:30

Statics are evaluated in the order they appear in the program.

查看更多
Viruses.
3楼-- · 2019-03-22 15:35

Besides answering the question of how the code is executed in what order, I am guessing you also want to know why a static block can refer to a static variable that has not been textually declared/executed yet.

While section 12.4.2 of the JLS does explain that static blocks and static variable are executed in the textual order that they appear, section 8.3.3 of the JLS explains when you can reference what, and you can see that the condition of The use is not on the left hand side of an assignment; fails, allowing your static block in the second example to refer to a static variable that has not textually in order been declared/executed yet.

查看更多
Melony?
4楼-- · 2019-03-22 15:42

Static blocks and static variables are initialized in the order in which they appear in the source. If your code is:

class Hello12 {

  static int b = 10;
  static {
     b = 100;
  }

}

The result is 100.

查看更多
beautiful°
5楼-- · 2019-03-22 15:47

In the "Detailed Initialization Procedure" for classes, Section 12.4.2 of the JLS states:

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.

This means that it's as if the first example was:

b = 10;
b = 100;

And the second example was:

b = 100;
b = 10;

The last assignment "wins", explaining your output.

查看更多
登录 后发表回答