[java] How can you run a Java program without main method?

Possible Duplicate:
Printing message on Console without using main() method

Can someone suggest how can a JAVA program run without writing a main method..

For eg:

System.out.println("Main not required to print this");

How can the above line be printed on console without using the public static void main(String arg[]) in the class.

This question is related to java

The answer is


public class X { static {
  System.out.println("Main not required to print this");
  System.exit(0);
}}

Run from the cmdline with java X.


Applets from what I remember do not need a main method, though I am not sure they are technically a program.


Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:

public class Foo {
    static {
         System.out.println("Message");
         System.exit(0);
    } 
}

The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:

Exception in thread "main" java.lang.NoSuchMethodError: main

In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).

Here an alternative is to write your own launcher, this way you can define entry points as you want.

In the article JVM Launcher you will find the necessary information to get started:

This article explains how can we create a Java Virtual Machine Launcher (like java.exe or javaw.exe). It explores how the Java Virtual Machine launches a Java application. It gives you more ideas on the JDK or JRE you are using. This launcher is very useful in Cygwin (Linux emulator) with Java Native Interface. This article assumes a basic understanding of JNI.