在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