Do we really understand public static void main(String[ ] args)?

Vishal AdityaVishal Aditya
2 min read

Why public?

The main method is public so that the JVM can access it from outside the class. JVM needs to call main method to start the execution of the program and making it public allows it to do so.


Why static?

The main method is static so that it can be called by the JVM without creating instance of the class. Since static methods belong to the class rather than any particular object, JVM can easily call it without having to bother about the object.

If the main method was not static then JVM would have to create an object for that class which would require either a constructor or some other way to initialize the object making the process more complicated.


Why void?

Void indicates the return type of the main method. Since the objective of the main method is to act as a starting point of the program it doesn’t make sense to assign any return type other than void.


Why the name main?

Main is the name of the method, this is the identifier that the JVM looks as the starting point of the program. If any other name was assigned then JVM would not be able to execute the program.


What is String[] args?

The parameter String[] args allows the program to accept command line arguments when it runs. args is an array of String objects, where each element is an argument provided in the command line when starting the program.

The main method needs a way to handle general input from command line, since most of the arguments are textual String[] is used.

The psvm method signature is a convention and required by the JVM to start the program execution. If we change it to something else it will not compile as a valid entry point for the Java application.

We cannot remove String[] args as the method signature needs to match the method definition provided by the JVM.



0
Subscribe to my newsletter

Read articles from Vishal Aditya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vishal Aditya
Vishal Aditya