java的静态代码块用static声明,在类被加载的时候调用。可以包含多个静态代码块,按照出现的顺序执行。静态代码块可以用来对类变量初始化。
代码示例:
package com.thb;import java.nio.channels.spi.SelectorProvider;public class Test1 {private static int number;static {number = Math.max(1, Runtime.getRuntime().availableProcessors());System.out.println("in static block1");}public static void main(String[] args) {System.out.println("in main method");System.out.println("number = " + number);Test1 test = new Test1();test.method();}static {System.out.println("in static block2");}public void method() {System.out.println("in instance method");}
}
执行结果: