In what order do static/instance initializer blocks in Java run?

前端 未结 8 1670
心在旅途
心在旅途 2020-11-22 17:01

Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in

8条回答
  •  佛祖请我去吃肉
    2020-11-22 17:51

    http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

    kindly check java documentation.

    then clearly mentioned no matter how may static blocks are there they will be executed as a single block in the order they appear

    So,

    My understanding here is java is looking your code as

    static{
    i=1;
    i=2;
    }
    

    static int i;

    that is why you are getting output 2

    hope this is helpful

提交回复
热议问题