Is main method compulsory in Java?
The answer to this question depends on version of java you are using. Prior to JDK 5, main method was not mandatory in a java program.
- You could write your full code under static block and it ran normally.
- The static block is first executed as soon as the class is loaded before the main(); method is invoked and therefore before the main() is called. main is usually declared as static method and hence Java doesn’t need an object to call main method.
- If run prior to JDK 5
program is running without main() method
- If run on JDK 6,7,8
Error: Main method not found in class Test, please define the main method as: public static void main(String[] args)
- How to overload and override main method in Java
- Static Block and main() method in Java
- Main thread in Java
- GFact 48 | Overloading main() in Java
- Valid variants of main() in Java
- Replacing 'public' with 'private' in "main" in Java
- Understanding public static void main(String[] args) in Java
- Execute main() multiple times without using any other function or condition or recursion in Java
- Does JVM create object of Main class (the class with main())?
- Understanding "static" in "public static void main" in Java
- Main App Implements Runnable | Concurrent Programming Approach 2
- Method Class | isDefault() Method in Java
- Method Class | getTypeParameters() Method in Java
- Method Class | getGenericParameterTypes() method in Java
- Method Class | toGenericString() method in Java
However, From JDK6 main method is mandatory. If your program doesn’t contain main method, then you will get a run-time error “main method not found in the class”. Note that your program will successfully compile in this case, but at run-time, it will throw error.
// This program will successfully run // prior to JDK 5 public class Test { // static block static { System.out.println("program is running without main() method"); } } |
Output:
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



