Hello world works but then gets error that there's no main?

前端 未结 6 609
星月不相逢
星月不相逢 2020-12-09 09:57

I have the following simple hello world in Java:

class A {
    static {
        System.out.println(\"Hello world\");
    }
}

It works as ex

6条回答
  •  情深已故
    2020-12-09 10:43

    When classes are loaded to the JVM, it first "process" what is in the static block, which is why it prints out "Hello World" first, which explains this part:

    class A {
        static {
            System.out.println("Hello world");
        }
    }
    

    When you run the program it looks for the "main" method, hence it prints out the Hello World first then looks for the main method, hence the error, same logic is applied when you call the method inside the static block.

提交回复
热议问题