Understanding Java-2

All about public static void main(String[] args)

JVM looks for the main method to execute the java program. The signature of the main method should be as defined above so that JVM can recognize it as the entry point.

  • public - It is an access specifier and signifies that the method can be accessed from outside the class. This is necessary because JVM is not present inside the class and it needs to invoke the main method. Thus it is made public to be accessed by the JVM.

  • static -A method defined with a static keyword attaches itself to the class instead of attaching itself to its instances. Thus, no object is needed to call the main method.

  • void - It is a return type that indicates a method doesn't return anything. When the main method terminates, the java program finishes executing and hence returning a value to JVM is of no use.

  • main - It is the name of the main method and JVM looks for this identifier specifically with the same name as its entry point.

  • String[] args - It is an array of type String class and stores the command line arguments. The name of the array could be different than args.

What if there is a main method without String[] args?

The code will compile but JVM won't be able to run it because it cannot recognize the main method as its entry point as JVM always looks for a main method with String type array as a parameter.