Can we execute a Java program without the main method

Java program to execute a program without the main method:

The main method runs when we run a class in Java. For example, if we create a Main.java file with the following code:

public class Main {
    public static void main(String[] args) {
        System.out.println("Inside main");
    }
}

and if we run this program, it will print the string Inside main.

But, if I remove the main method,

public class Main {
    public void hello() {
        System.out.println("Inside main");
    }
}

It will throw an exception:

Error: Main method not found in class com.company.Main, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Java program without main exception

How to run a Java program without the main() method:

We can write a Java program without the main method with a static block only up to Java 1.5. A static block is written with the static keyword. This method runs as soon as the class file is loaded to the memory. You have to write your code in the static block:

static{
    // your code
}

You can have more than one static block. These blocks are executed before the main method. The execution order is similar to the order these are added to the class. If you need to run anything before the main method executes, you can add the code in a static block.

So, the below program will work(upto Java 1.5):

public class Main {
    static {
        System.out.println("Inside main");
    }
}

For the later Java versions, we don’t have any other way to run a program without the main method.

You might also like: