Thursday, June 7, 2007

Run a Java program without the main method

Here is an example of how to run a java program without the main method ...
public class HelloWorld{
static{
System.out.println("Hello World!");
System.exit(0);
}
}

Display: Hello World!

Now let us test the program without System.exit(0). The program will terminate complaining that there is no main method.

public class HelloWorld{
static{
System.out.println("Hello World!");
//System.exit(0);
}
}

Display: Hello World!
Exception in thread "main" java.lang.NoSuchMethodError: main

No comments: