Saturday, August 4, 2007

Write a Java Application without a main() method

Here we are.. this time with a small Java tip.. being Java fans..we just cant wait to post on Java. So, decided to start of with something which most of us might not be aware of.
You can write a runnable Java program which does not have main method at all. This can be done using the static block of the class.

The reason this works is that static initialization blocks get executed as soon as the class is loaded, even before the main method is called. During run time JVM will search for the main method after exiting from this block. If it does not find the main method, it throws an exception. To avoid the exception System.exit(0); statement is used which terminates the program at the end of the static block itself.

class MainMethodNot
{ static
{
System.out.println(“This java program has run without the main method”);
System.exit(0);
}
}

No comments: