Difference between the static initializer block and regular static initialization

后端 未结 8 2046
广开言路
广开言路 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条回答
  •  梦毁少年i
    2021-01-05 12:24

    Difference between static initializer block and regular static initialization.

    In case of variable initialization both are same.

    But If we want to connect with database only once or any operation you want to load once. Then write the code in static block because its execute only once when first class load no matter how many objects of that type you create.

    EDIT :

    You can also construct a similar block:

    {
        // Do Something...
    }
    

    Example:

    public class Demo {
    
        static{
            System.out.println("Static");
        }
    
        {
            System.out.println("Non-static block");
        }
    
        public static void main(String[] args) {
            Demo demo = new Demo();
            Demo demo2 = new Demo();
        }
    }
    

    Output:

    Static

    Non-static block

    Non-static block

提交回复
热议问题