Browse DevX
Sign up for e-mail newsletters from DevX


Tip: Using a Java File with an Empty Main Method

Java programs cannot be executed without a standard main method. Learn an work around to cheat the requirements.


This is sort of like cheating the Java runtime. Ideally, I believe, starting Java 1.6, you cannot execute Java programs without a standard main method. Prior to that, only the static block was sufficient.

You actually do not have to create an instance of the file, but a skeletal main method is required.

public class JavaFileWithEmptyMain{ 

   //static block - No class instance needed
      System.out.println("In static block"); 
      String staticVariable = "Variable in static block";
      System.out.println("Value of staticVariable: " + staticVariable); 
   public static void main(String args[])
      // No implementation - empty 



Expected output:

Case 1: When the main method does not exists or commented.

[root@mypc]# java JavaFileWithEmptyMain
Error: Main method not found in class JavaFileWithEmptyMain, please define the m
ain method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Case 2: As per the above code

[root@mypc]# java JavaFileWithEmptyMain
In static block
Value of staticVariable: Variable in static block



Visit the DevX Tip Bank


Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date