Create a Program Without a Main Method in Java



Java is a statically typed, object-oriented programming language that needs a main method as an entry point for running. But it is possible to develop Java programs without a main method under certain conditions.

Different Approaches

The following are the different approaches for creating a program without a main method in Java ?

Using Static Blocks (Before Java 7)

In previous implementations of Java (prior to Java 7), a program was possible to run with a static block, even without a main method. The static block is executed when the class is loaded.

  • The static block is executed automatically when the JVM loads the class.
  • System.exit(0); stops any main method exception from being thrown.

Note: In Java 7 and later, the JVM needs a main execution method.

Example

Below is an example without the main method using static blocks ?

public class Test {
    static {
        System.out.println("Hello, this is executed without a main method!");
        System.exit(0);  // Terminate the program
    }
}

Using a Servlet

Java Servlets do not need the presence of a main method whereas the servlet container like the Apache Tomcat serves as the environment in which Java Servlets are run.

Techniques such as doGet() and doPost() of the servlet are executed instead. The servlet container (e.g., Tomcat) performs the execution of the servlets, handling incoming HTTP requests, and calling the corresponding methods.

Example

Below is an example without the main method using a Servlet ?

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyClass extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("Hello");
    }
}

Using a JavaFX Application

JavaFX applications use the start() method instead of the main method.

Example

Below is an example without the main method using the JavaFX application ?

import javafx.application.Application;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.scene.Scene;


public class MyClass extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setScene(new Scene(new Label("Hello, JavaFX!"), 300, 200));
        primaryStage.show();
    }
}

Conclusion

Although the main method is essential for standard Java applications, alternative execution methods exist. Techniques such as static blocks (pre-Java 7), servlets, and JavaFX allow Java programs to run without explicitly defining a main method. 

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-18T11:15:51+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements