static关键字可以用来修饰类、方法、代码块和变量。
输出结果为:
Hello
World
i = 0
World
i = 1
World
i = 2
World
i = 3
World
i = 4
结论:static代码块在类加载时运行,而且只加载一次,加载完毕后类才开始实例化。
public class StaticTest {
/**
* @param args
*/
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
Test test = new Test();
test.print();
System.out.println("i = " + i);
}
}
}
class Test {
static {
System.out.println("Hello");
}
public void print() {
System.out.println("World");
}
}
输出结果为:
Hello
World
i = 0
World
i = 1
World
i = 2
World
i = 3
World
i = 4
结论:static代码块在类加载时运行,而且只加载一次,加载完毕后类才开始实例化。