0

The following code gives error because i am not put static keyword to main method. Please explain why main method not working without static keyword.

public class Test {
public void main(String args[]) {
    try {
        int a = new Integer(10);
        System.out.println(a);
    } catch (Exception e) {
        System.out.println(e);
    }
}

}

Error:Main method is not static in class Test, please define the main method as: public static void main(String[] args)

  • Because there is not class instance from which the JVM can call the `main` method. It's a requirement of the language, why should it be anything else? – MadProgrammer Sep 09 '14 at 06:51
  • Because it makes no sense to put a "entry" function at instance level. Also, It will be present when a class is loaded. The JVM doesn't need an instance of `Test` to call it. – TheLostMind Sep 09 '14 at 06:51

1 Answers1

2

Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.

If main method were not declared static than JVM has to create 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 main method in Java.

also refer this for detailed and very well explained answers.

Community
  • 1
  • 1
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116