Search code examples
program-entry-pointjava

Where is Java Main method defined in source?


Pardon me for asking this silly question. Where can i find java main method definition in java source? it is not in object class or system class? so how and where is it defined exactly?

public static void main(String[] args) {}

Solution

  • Where is Java Main method defined in source?

    It is declared in a class. Conventionally, it is a top-level (i.e. non-nested) public class, but that is not a requirement. (A non-public class will work, and I think a static nested class will work too.)

    How do you find the main method?

    • Use grep or similar to search the source code of your application.

    • Use your IDE's method search capability.

    • Read the application's user documentation or launch script.

    • Look for the main method in the index of the application's javadoc.

    How does the java command find it?

    It doesn't! You specify the fully qualified class name of the class containing the main method you want to use on the java command line. Alternatively, you can set the Main-Class attribute in a JAR file's manifest so that the user doesn't need to know the class name.


    UPDATE - If you are looking for the code in the OpenJDK source tree that loads the entrypoint class, finds the main method and invokes it, it is all in "jdk8u/jdk/src/share/bin/java.c". Happy reading.