Here is a somewhat detailed explanation of why the main method is declared as
public static void main(String[] args)
The primary method is the entry point of the Java program for the Java Virtual Machine (JVM). Let them say that we have a class called Sample
class Sample { static void fun() { System.out.println("Hello"); } } class Test { public static void main(String[] args) { Sample.fun(); } }
This program will be executed after compilation as java Test . The java command will launch the JVM and load our Test.java class into memory. Since the main entry point to our program, the JVM will look for the main method declared as public , static and void .
Why should main be declared open?
main() must be declared public , because, as we know, it is launched by the JVM when the program starts, and the JVM does not belong to our program package.
In order to access the main external side of the package, we must declare it as public . If we declare it as something other than public , it will display a Run time Error , but not a Compilation time error .
Why should main be declared static?
main() must be declared as static because the JVM does not know how to create a class object, so it needs a standard way to access the main method, which is possible by declaring main() as static .
If a method is declared static , we can call this method outside the class without creating an object using the syntax ClassName.methodName(); .
So the JVM can call our main method as <ClassName>.<Main-Method>
Why should main be declared invalid?
main() must be declared invalid because the JVM does not expect a value from main() . Therefore, it must be declared as void .
If a different return type is provided, this is RunTimeError ie, NoSuchMethodFoundError .
Why should main have string array arguments?
main( ) must have String arguments as arrays because the JVM calls the main method by passing a command-line argument. Since they are stored in a string array object, it is passed as the argument to main() .