Public static void main in java is main method in java.
In this tutorial we will see main method in java,public static void main , syntax of main method.
Main method is the main part of any programs from where the execution of the programs starts.
In c or cup we simply write void main() method but, java has different signature for writing the main method.
Main method in java
Signature for declaring the main method in java is as follow
java main method syntax
public static void main(String args )
The signature consist of
This is the access specifier which is used to call main method from anywhere
It is access modifier. Without existing object of the class JVM has to call main method and main method no way related to any object.
In java, JVM calls the main method, and returning to JVM has no use that is why void is specified as return type of main.
main() is the name of the function like other user defined method. This is the entry point from where the execution begins.
By changing the prototype of main() will not give any compile time error bit gives the runtime exception saying Nosuchmethod:main
Their are some changes in main which are accepted
Order of modifiermodifier is not important.
We can use any other identifier instead of string args
We can declared main as final,synchronised.
Why use public static void main in java?
=> The reason beside why we write main(method name) because this is the name which is configured inside the JVM. Whenever JVM finds the main it’s start executing code.
What is String args in java?
Is array of string which is mostly used for passing the command line argument.
Whenever user passes argument from command prompt that argument are stored in args.
What happened when we don’t write main method in program ?
If we don’t write main method or if we don’t wrote main according to requirements(syntax), the compiler won’t check theses things.
But at runtime, JVM responsible to check those things. If JVM unable to find main ()it gives the exception. JVM also check for prototype of main()
Why JVM search for main()
In JVM it has a definition of main method from where program execution starts.
Can we change name of main method
Yes, we can change the name of main but for execution we need to configure in JVM that’s why mostly we use main only.
Can we overload main method
Yes, we can overload main method but JVM always calls string array argument only. Other overloaded method we have to call explicitly.