Java面试题—如何实现在main()方法执行前输出“Hello World”

  众所周知,在 Java语言中,main()方法是程序的入口方法,在程序运行时,最先加载的就是main()方法,但这是否意味着main()方法就是程序运行时第一个被执行的模块呢?
  答案是否定的。在Jawa语言中,由于静态块在类被加载时就会被调用,因此可以在main()方法执行前,利用静态块实现输出“ Hello World”的功能,以如下代码为例。

public class Test{
    static{
        System.out.ptintln("Hello World1");
    }
    public static void main(String[] args){
        System.out.ptintln("Hello World2");
    }
}

程序运行结果为:

Hello World1
Hello World2

由于静态块不管顺序如何,都会在main()方法执行之前执行,因此,以下代码会与上面的代码有同样的输出结果。

public class Test{
    public static void main(String[] args){
        System.out.println("Hello World1");
    }
    static{
        System.out.println("Hello World2");
    }
}

欢迎进群交流258897306或关注公众号“IT群英汇

猜你喜欢

转载自blog.csdn.net/qq_42308454/article/details/82886988