|
You can thus execute any class from command line as long as the class contains the main() method. But this main() method cannot be just any method with the name main. It must follow a particular method signature:
public static void main(String[] args)
The Java interpreter java can find and invoke a main method only when the method follows the above signature. That is when it is static, public, takes a single string array argument and returns nothing. The main method is static and public for a good reason. Since it is static , the JVM can call it without any need to create an instance first. Since it is public , it is accessible from outside the class.
You may define the main method with a different signature, but when you try to run the application, the JVM will try to search for the main() method with the above mentioned method signature. If it fails to find it, it will flag a runtime error. The table 8.1 compares the output for main method with different signatures.
Table 8.1 Comparison of compile-time and runtime behavior of the main methods with different signatures.
|
|
main method as application’s entry point in class Test1 |
Ordinary main method in class Test2 |
What happens? |
|
Source code |
public class Test1 { public static void main(String[] args) { System.out.println("Test1"); } } |
public class Test2 { public void main(String[] args) { System.out.println("Test2"); } } |
|
|
Compiling the source code |
$ javac Test1.java
|
$ javac Test2.java
|
Both the class definitions compile successfully |
|
Executing the .class files |
$ java Test1 Test1
|
$ java Test2 Exception in thread "main" java.lang.NoSuchMethodError: main |
JVM can execute only Test1.class as an application. |
Note that the class definition for Test2 compiles successfully. The only reason it fails to run as a java application is that it does not have a main method with exact signature that the JVM is looking for at the runtime.
|
|
For the exam, whenever you see a question based on main method, you can safely assume that it is about the main method used to invoke a java application unless it is explicitly specified to be otherwise. |
Except for the fact that it is invoked by JVM, there is nothing special about the main method. It behaves like any other (static) method of a class. You can also change the order of its modifiers and it will still be a valid main method and can be found by JVM at runtime. For instance, both of the following are valid declarations of main method.
static public void main(String[] args) {}
public static void main(String[] arguments) {}