【java】在主函數前輸出hello world

  在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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章