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.
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.
When JVM runs an application by specifying a class, it will look for the main method with the signature of public static void main(String[])
.
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.