1. Question: Why is the Java Main method public static void main (string[] args)???
| Serial number |
Scene |
Compile |
Run |
Explain |
| 1 |
Public change to private protected or remove |
Normal |
Main Method not Public |
only when Main method is not on the public level. JVM visible, so you need to use Public Retouching |
| 2 |
Remove Static |
Exception in thread "main" Java.lang.NoSuchMethodError:main |
if you want to make Main method as a program entry, you do not have to first create the class instance but call directly, so the method needs to use Static Retouching |
| 3 |
Modifying the return value type |
The JVM is already at the bottom of the Java program, and the return value of the method it calls is nowhere to go, so the main method does not need a return value, so use the void modifier |
| 4 |
modifying parameter types or adding multiple parameters |
The main method needs to receive the arguments passed in from the command line (separated by spaces), andthe Java specification uses a string array as the unique input parameter of the main method, and the parameter name can be not args, If the parameter is not worn, the array is Empty and not NULL |
| 5 |
Modify Method Name |
contain Main the class of the method is Java Application, JVM only Identify Main as a program entry, you can only use Main as the method name |
| 6 |
Add Throw Exception |
Normal |
The main method can throw an exception |
| 7 |
Public and static interchange Locations |
Normal |
|
2. Problem: Main method as the entrance of the program
1 Public classMain2 {3 Static4 {5System.out.println ("123");6System.exit (0);7 }8 9 Public Static voidMain (string[] args)Ten { OneSystem.out.println ("456"); A } -}
Run Result: 123
When the JVM executes, it loads the class first, then executes the inner static block, and then calls the main method.
The static block print "123" in the previous example is forced to exit the program, and there is no chance to execute the main method.
The Java Main method