在java語言中,main()方法是整個程序的入口,程序在運行時最先加載的就是main()方法,但是這並不意味着main()方法就是程序運行時第一個被執行的模塊。
在java語言中,靜態代碼塊在類被加載時就會被調用,因此可以在main()方法前就執行,利用靜態代碼塊實現在主函數之前輸出hello world
public class staticc { static { System.out.println("hello world"); } public static void main(String[] arg) { System.out.println("say hello to the world"); } }
輸出:
hello world
say hello to the world
執行順序與靜態代碼塊的位置無關
public class staticc { /*static { System.out.println("hello world"); } */ public static void main(String[] arg) { System.out.println("say hello to the world"); } static { System.out.println("hello world"); } }
輸出:
hello world
say hello to the world