jack-zheng
9/19/2018 - 9:48 AM

static, block, java, syntax

static, block, java, syntax

Static Block In Java

  • used for initializing static variable
  • execute when class loaded in memory
  • class can have multiple static block
  • multiple static block execute in order
  • execute before constrctor
    • constructor 是关联对象的, static 是关联class 的必然要比构造先执行
// sample class
package staticblock;

public class StaticBlock {
    static int num;
    static String name;

    static {
        System.out.println("Call static block");
    }

    static {
        System.out.println("Assign value to num");
        num = 1;
    }

    static {
        System.out.println("Assign value to name");
        name = "jack";
    }

    public StaticBlock() {

        System.out.println("Call constructor");
    }
}

// test class
package staticblock;

public class StaticBlockTest {
    public static void main(String[] args) {
        StaticBlock sb = new StaticBlock();
    }
}

Console Output

Call static block
Assign value to num
Assign value to name
Call constructor

Process finished with exit code 0