Why is the main method public static void?

The main method is the first method we come into contact with when we learn java. When we were learning, it was stipulated that the main method was written in a fixed way:

public static void main(String args[])

So, why the main method must be of public static void type?
When the JVM starts, it will look for the public static void main(String args) method as the entry. If the method is not found, the error NoSuchMethodError: main program is terminated.

Why is the main method public?

Java specifies some accessible modifiers such as: private, protected, public, any method or variable can be declared as public, and Java can be accessed from outside the class. Because the main method is public, the JVM can easily access and execute it.


Why the main method is static (static)

  1. Because the main method is static, the JVM does not need to create any instance containing the main method to call this method.
  2. Because C and C++ also have a similar main method as the entry point for program execution.
  3. If the main method was not declared static, the JVM would have to create an instance of the main class, and since the constructor can be overloaded, the JVM would not be able to determine which main method to call.
  4. Static methods and static data are loaded into memory and can be called directly without creating an instance like instance methods before they can be called. If the main method is static, it will be loaded into the JVM context to become an executable method.

<strong>Why the main method has no return value (Void) </strong>
Because main returns no value to the program has no meaning, so it is designed as void, which means that main will not return any value

<strong>Summary</strong>
The main method must be declared as public, static, void, otherwise the JVM cannot run the program
Throws a NoSuchMethodError: main exception if the JVM cannot find the main method, for example: if you run the command:

java HelloWrold
The JVM will search for public static void main (String[] args) in the HelloWorld.class file.
The main method is the entry point of the program, the beginning of the program execution.
The main method is run by a specific thread "main", and the program runs until the main thread ends or the non-daemon thread terminates.
When you see "Exception in Thread main" like:
<strong>Excpetion in Thread main: Java.lang.NullPointedException</strong>, means that the exception comes from the main thread

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326015854&siteId=291194637