Why main Method static in Java

When you write any Java program it’s starting execution point is the main method which has a form as following.

Given this signature of main method in Java the question arises why main method is public, void and static in Java. It is asked quite frequently in interviews too.

Why Java main method is marked public

Having an access modifier as public means method can be accessed from classes in the same package and from other packages too.
Main method in Java is public so that JVM can easily access it, as JVM needs to load the class and call the main method of the class.

Why Java main method is void

Any Java method which doesn’t return a value has to be marked as void. Since main method in Java doesn’t return any value so it is void.

Why Java main method is static

The point why main method is static in Java needs some explanation.

When any method is marked as static in Java, it is associated with the class not with any object of the class. Any static method can be called without creating any object of the class.
For example-

You can call methodA using the class itself – Test.methodA(); as it is a static method.
You don’t need to do this-

As we know main method in Java is the starting point for the execution of the program and marking the main method as static means JVM can call main method with out creating any instance of the class.
You may think what if the instance is created and main method is called using that instance of the class, answer is that will cause ambiguity if there are constructors with arguments in your class.
For example consider this class-

If JVM has to create an instance of this class and then call the methods, then constructor of the class has to be invoked. In that case what value has to be passed for i, if JVM has to create an instance itself.

It has to execute this statement – Test test = new Test(7); to create an instance of the class initialized with the passed value. To call this statement, method has to be called with out creating any object of the class, so we are back to the fact that the method has to be static. That is why main method is static in Java .

Important points

  1. If you don’t declare main method as public void static, there won’t be a compile time error but run time error will be thrown.
    If main method is not static

    If main method is not public static
  2. With varargs Java 5 onwards main method signature can also be as follows-
  3. Having main method as static in Java is required so that the main method which is the starting point for the Java program can be executed with out creating instance of the class.

That’s all for the topic Why main Method static in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.