RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Jan 24, 2019

Using a Java File with an Empty Main Method

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

M S Sridhar
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date