DEV Community

Shubham Rathi
Shubham Rathi

Posted on

Why main method in JAVA is declared in Static?

The main() method is declared static so that JVM can call it without creating an instance of the class containing the main() method.

What if the main method is not static?

If the main method of the java class is not static then it will throw an error, here you can try this code on any java compiler and it will throw the error.

Moreover, if a JAVA class is declared without a static keyword, the JVM has to create an instance of the main Class, and because the constructor might be overloaded and include arguments, there will be no reliable and consistent way for the JVM to find the main method in Java.

public class MyClass {
    public void main(String args[]) {
      System.out.println("Hello World!!");
    }
}
Enter fullscreen mode Exit fullscreen mode
Error: Main method is not static in class MyClass, please define the main method as:
   public static void main(String[] args)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)