简体   繁体   中英

Why is a static method called main launchable?

I guess there's something about jvm.BUT how does jvm recognize it?For the name main,or the static property?

That's my little confusion.

当 JVM 通过指定一个类来运行应用程序时,它会寻找带有public static void main(String[])签名的 main 方法。

TLDR; Neither having a main method nor a static method is sufficient, and the method needs to be both, as specified by the Java Language Specifications (JLS).

If there is something about the JVM then it is usually specified in the Java Language Specifications. In this case it is section 12.1 which specifies the requirements for a main method:

public static void main(String[] args)

or

public static void main(String... args)

So instead of just being static it also needs to be public and have a void return type (integer makes more sense maybe, but Java is multithreaded, so the return value is given using System.exit(int) ). Furthermore, it must accept String arguments, as you would expect.

Note that the main method has been designed to be used in a CLI environment such as the command line in Windows or one of the many shells in Linux / Unix / MacOS. It is similar to the C/C++ main method; Java was based on the C/C++ language.

I've also checked this against Java 18, and the text is still the same.

Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args) .

When java runtime starts, there is no object of the class present. That's why the main method has to be static so that JVM can load the class into memory and call the main method. If the main method won't be static, JVM would not be able to call it because there is no object of the class is present

You can find a detailed explanation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM