Difference between the static initializer block and regular static initialization

后端 未结 8 2061
广开言路
广开言路 2021-01-05 12:12

As the title says, what exactly is the difference between

public static String myString = \"Hello World!\";

and

public stat         


        
8条回答
  •  臣服心动
    2021-01-05 12:15

    For your example, there is no difference. But as you can see,

    public static String myString = "Hello World!";
    

    can only accept an expression to initialize the variable. However, in a static initializer (JLS 8.7), any number of statements may be executed. E.g. it's possible to do this:

    static
    {
        myString = "Hello";
        myString += " ";
        myString += "World";
    }
    

    For your example, there's obviously no need to do that, but it's possible for the initialization of a variable to take more than an expression, perhaps many statements, so Java made static initializers.

提交回复
热议问题