Write a Java Program to execute program without main() method.

Yes. In Java, we can write a class without explicitly defining a main() method. For example, using a static initializer block:

In older Java versions, you could use a static block:

class JavaKnowledgeBase{
    static {
        System.out.println("Java Knowledge Base");
        System.exit(0);
    }
}

Traditionally, this could execute the static block when the class is initialized, but modern Java versions require a main method when launching a class directly. So this is not a reliable way to run a standalone program on current Java versions.

How does this work?

Step 1: Class loading

When Java loads the Demo class, it initializes its static members.

Step 2: Static block executes this code

static {
    System.out.println("Java Knowledge Base");
}

runs during class initialization.

Step 3: Output

You get:

Java Knowledge Base

Step 4: System.exit(0)

System.exit(0);

terminates the JVM normally after printing.

⚠️ Important for modern Java

This trick is version-dependent and should not be used as a normal Java program technique. In modern Java, launching a class with java Demo expects a valid application entry point (main, subject to the Java version’s launch rules).

So if this is an interview question, you can say:

“Yes, a class can contain executable code in a static initializer without declaring main(), but whether it can be launched directly without main() depends on the Java version. The traditional static-block trick is mainly a historical example.”

So how do we write it in Java 21?

The normal Java 21 program is still:

class JavaKnowledgeBase {
    public static void main(String[] args) {
        System.out.println("Java Knowledge Base");
    }
}

However, Java 21 has a preview feature that allows simpler entry-point syntax. For example:

class JavaKnowledgeBase {
    void main() {
        System.out.println("Java Knowledge Base");
    }
}

But you need to enable the preview feature when compiling/running.

javac --enable-preview --release 21 JavaKnowledgeBase.java
java --enable-preview JavaKnowledgeBase

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *