Question #168631

Why is method main declared static


Expert's answer

Java's main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class.

  • In any Java program, the main() method is the starting point from where the compiler starts program execution. So, the compiler needs to call the main() method.
  • If the main() is allowed to be non-static, then while calling the main() method JVM has to instantiate its class.
  • While instantiating it has to call the constructor of that class, there will be ambiguity if the constructor of that class takes an argument.
  • The static method of a class can be called by using the class name only without creating an object of a class.
  • The main() method in Java must be declared publicstatic, and void. If any of these are missing, the Java program will compile but a runtime error will be thrown.

Example

class Book {
   public static void getBookInfo() { //static method
      System.out.println("Welcome to TutorialsPoint Library");
   }
}
public class Test {
   public static void main(String[] args) {
      //Call static method of Book class using class name only
      Book.getBookInfo();
   }
}

Output

Welcome to TutorialsPoint Library




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS