Home >Java >javaTutorial >Why is the `main` method in Java declared as `static`?
Java Main Method: Why the Static Declaration?
The Java main method has a specific signature:
public static void main(String[] args) { ... }
This raises the question: is the static modifier essential for the main method?
Convention, Not Requirement
Contrary to the initial impression, the static declaration for the main method is a convention, rather than a linguistic necessity. It may surprise you, but even the method name "main()" and the String[] parameter are merely conventions.
Alternative Conventions
Java 21 introduced alternative conventions that allow for the omission of the String[] parameter, the public modifier, and even the static modifier. In the absence of the static modifier, an instance of the class will be created prior to the main() invocation, requiring the class to have a non-private zero-parameter constructor.
Java Native Interface (JNI) and java.exe
The execution of a Java program through java.exe (or javaw.exe on Windows) involves JNI calls that load the JVM as a DLL. JNI serves as a bridge between the JVM and C/C environments.
java.exe: A Simple C Application
java.exe is essentially a simplified C application that parses command-line arguments, creates a String array within the JVM, locates the main() method in the specified class using JNI, and invokes it with the argument array. This process resembles Java reflection, using native function calls instead.
Customizing java.exe
It is possible to modify the source code of java.exe (provided with the JDK) to alter its functionality. This is employed in Java-based applications to customize the launcher, provide unique icons, and handle specific scenarios (e.g., passing COM handles to main()).
Convenience and Historical Influence
The static nature of the main method offers convenience and aligns with the naming convention adopted from C. It empowers IDEs to auto-detect launchable classes within a project. Although alternatives exist, the "static" main method persists as a ubiquitous convention in Java programming.
The above is the detailed content of Why is the `main` method in Java declared as `static`?. For more information, please follow other related articles on the PHP Chinese website!