Why the main() Method Is Public Static

Let's first see why the main() method is static and public with an example.

Why the main() method is static

The main() method is static Java Virtual Machine can call it without creating an instance of a class that contains the main() method.

If the main() method was not declared static than JVM has to create an instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find the main() method in Java.

For example: In the below example, while creating instance ambiguity might arise when the constructor takes an argument as to which one to call.
package net.javaguides.corejava;

public class MainMethodDemo {

    public MainMethodDemo(int arg0) {
        //One argument constructor
    }

    public MainMethodDemo(int arg0, int arg1) {
        //Two arguments constructor
    }

    public MainMethodDemo(String arg[]) {

    }

    public void main(String...args) {
        //Non Static main method
    }
}

Why the main() method is public

Java specifies several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessed from outside of that class. Since the main method is public in Java, JVM can easily access and execute it.

For example, the main() method should be public
public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
}



Comments