Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
270 Members
Join this group to post and comment.
Shruthi Pillai
Shruthi Pillai
Information Technology
12 Feb 2019

Can you compile a Java class successfully without having the main method?

Yes, we can compile, but it won't run. The main method works as the startup function for a Java class, and the JVM calls it for the program execution.

AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
3mos ago

We can run the java program without the main method by writing code in static initializer block which is half true.The code written in static initializer block is executed before calling main method,but you won't be able to run a class by using Java command or eclipse or anything else,until it got public static void main(String args[]) method in it.If we try to run such programs the we get the following error:

Main method not found in class.Please define the main Method.

We can run the java program with empty main method in which case only code executed will be from static intializer block, including a print statement,a variable intialization and starting a thread.As soon as we remove the main method it will complie but will throw the above error.

But in short we can run Java programs without main method in a managed,servlet which runs under control of browser, server and mobile device,but cannot run a core java program without the method.JVM will not allow us to execute those methods.