- Introduction to JVM Languages
- Vincent van der Leun
- 262字
- 2021-07-02 21:46:30
At least one class must have a static main() method
When running a JVM application manually with the java command, you'll need to specify the class that has the following static method:
public static void main(String[] args) {
}
This is the method that will be called by the java command after the JVM instance has finished initializing. It is comparable to C's and C++'s well-known main() entry point function. The string array args will contain the command-line parameters as passed by the operating system.
The preceding snippet illustrates Java code. Some JVM languages do not require the programmer to write this method manually; they automatically generate one when compiling the class. Also, some JVM frameworks automatically generate or provide this method.
There can be slight variations of the main() method, though:
- The name of the method's parameter is not important. The args is the convention. Sometimes argv is used, but something similar to arguments would also be fine.
- There can be variations of the argument type. A string array (in Java, String[]) is usually used, but a var args parameter (String..., covered in the next chapter) would work as well.
Here's an example of a valid main() function in Java with the string's var args parameter type and a different argument name:
public static void main(String... commandLineArguments) { }
There can be more than one class with a static main() method in your project. But only one can run at a time. The fully qualified class name must be specified on the command-line when running the application with the java command.