Difference between the static initializer block and regular static initialization

后端 未结 8 2060
广开言路
广开言路 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:18

    Well, in your first example the variable is declared and initialized on the same line. In your second the variable is first declared, then initialized. In the second case you could have any number of other static variable and block initializations occur before getting to the initialization block in question. Consider this case:

    public static String myString = "Hello World!";
    public static String yourString = myString;
    static {
        System.out.println(myString);
        System.out.println(yourString);
    }
    

    vs:

    public static String myString ;
    public static String yourString = myString;
    
    static {
        myString = "Hello World";
    }
    
    static {
        System.out.println(myString);
        System.out.println(yourString);
    }
    

    Output from the first example:

    Hello World
    Hello World
    

    Output from the second example:

    Hello World
    null
    

提交回复
热议问题