First Program of Java : SECTION 2

We wrote our first simple hello world program, so let’s check what is the significance of each keyword in the public static void main(String args[]) method and why we must use that to run our program.

public

This is the access modifier for our main method. JVM is an outsider for our class and if it wants to access the method inside our class then it should have public access. This means that to run our main method it has to be public. If we remove the public keyword, re-compile, and run again it will give Runtime Error as shown.

First Program of Java

So Can we use any other access modifier than public? The answer is No. else we will get the above exception while running the code.

static

Note that while calling the main method we are not creating any object. JVM is directly calling the main method in the class via class name. So to make it available for direct call by JVM without any object creation we should declare our main method as static. If we remove the static keyword from our program, compile, and re-run again we will get the following Error.

First Program of Java
void

This is the return type of the main method. Since our main method does not return any value this type is void. It is mandatory in java programs that every method should have a return type. JVM always searches for the main method with void as a return type. If we change the return type in our code to String and add a return statement we will get an error as shown.

First Program of Java
main

This is the name of the method. We can give any name for our method. But when running JVM always search for this method name. If no main method is found, then when running the code we will get an error saying “Main method not found in class HelloWorld”. This is the same error we got when we removed the public keyword.

Can we change the main method name to any other name?

Yes, we can, but JVM is internally build to search for the main method name by default while running. If we want to change the name of the main method into something else, we also need to do code changes in JVM to check for a new method name instead of the main.

String args[] or String[] args

This is the input parameter to our main method. Java’s main method accepts a single argument of String array type. args is a variable name, we can give any other name instead of args.

So we got an overview of our main method and why each keyword is used. Next, we will see how to pass arguments to our code and how to read the same.

-A blog by Shwetali Khambe

Related Posts