Java面試題(每日兩題9.28)—如何實現在main()方法執行前輸出“Hello World”
阿新 • • 發佈:2018-12-12
眾所周知,在 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群英匯 ”