devxlogo

Using a Java File with an Empty Main Method

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   static    {       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 JavaFileWithEmptyMainError: Main method not found in class JavaFileWithEmptyMain, please define the main 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 JavaFileWithEmptyMainIn static blockValue of staticVariable: Variable in static block*/
See also  Java Developer Jobs: Your Guide to Landing the Perfect Position in 2024
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist