众所周知,在Java语言中,main()方法是程序的入口方法,在程序运行时,最先加载的就是main()方法,但这是否意味着main()方法就是程序运行时第一个被执行的模块呢?
答案是否定的。在Java语言中,由于静态块在类被加载时就会被调用,因此可以在main ()方法执行前,利用静态块实现输出"Hello World"的功能,以如下代码为例。
public class Test{
static{
System.out.println("Hello World1");
}
public static void main(String args[]){
System.out.println("Hello World2");
}
}
程序运行结果为:
Hello World1
Hello World2
由于静态块不管顺序如何,都会在main()方法执行之前执行,因此,以下代码会与上面的代码有同样的输出结果。
public class Test{
public static void main(String args[]){
System.out.println("Hello World2");
}
static{
System.out.println("Hello World1");
}
}