Wednesday, August 22, 2007

How to print Hello World ! without using main in Java?

This is probably a very old question, but as the blog title goes, I just discovered it today.


//Example.java

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

javac Example.java
java Example

The code is stunningly simple. But there are some good concepts involved in it.
1. Always static blocks are executed first.
On typing java Example, JVM first loads that class, which starts with initializing static variables followed by static blocks and then static methods.
2. JVM searches for public static void main(String[] abc) while executing a class.
If JVM does not find it, it throws a java.lang.NoSuchMethodError. But here in the above example, even before letting the JVM do that, System.exit(0) is called.

Solution might look easy after seeing it. But its always the case, isnt it ???

No comments: