The main() method in Java

Beginners Code Computer Skills Java Mobile Development Web Development

We are already familiar with the signature of the main method in Java. We have used in all the programs so far. You will get a detailed analysis of the main method.

Characteristics of the main() method in Java:

  • The entry point of any Java program is the main() method.
  • A program starts to execute only if it finds a main() function inside it. Therefore, it is mandatory for a java application to have a main() method.
  • In Java, main() is user defined but the signature of the main() method is predefined.
    • The prototype is predefined
    • The body/logic inside the main method is user-defined
    • public static void main(String[] args) {}


main() method in Java

  • The compiler compiles the Java program into .class files containing intermediate byte code.
  • The JVM then calls the main method to start the execution of the .class files.
  • However, the compiler never checks for the existence of main() method but JVM always starts the execution from the main() method inside the class file.

Why is the main() method public and static in Java?

  • The .class files are created after compilation of a Java program.
  • JVM is a built-in system software whose job is to execute these .class files.
  • It starts the execution from the .class file that contains the main() method.
  • The main() method is called by JVM from the OS, which is outside the current package of the program.

So the main() method must be declared as public so as to make it accessible outside of the package.

Now for the static part,

  • A static method can be called directly with the class name. There is no need of creating an object to access the static method.
  • The main() method is called by JVM with the name of the class.

Therefore the main() method is static in Java.

Why is the return type void for the main() method in Java?

  • If a method does not return any value, the return type must be void in Java.

The main() method never returns any value to JVM, and so the return type is void.