Monday, December 18, 2006

Program Without Class Keyword

Here is how you can write a standalone Java program WITHOUT a class keyword:

enum E{
X;{
System.out.println("Hello World");
System.exit(0);
}
}

Here is how you can write a standalone Java program WITHOUT a main method:

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

To avoid the "Could not find main method" exception, the System.exit(0); statement is used which terminates the program after printing out Hello World.

Update (1/1/2013): These examples work on older versions of Java but not on Java 6 and above.

1 comment:

Note: Only a member of this blog may post a comment.