Thursday, March 01, 2007

The Shortest Java Program Ever

Java programs does not need to be long... This is the shortest Java program that you could possibly make:



The program contains absolutely no code at all. Name the program Nothing.java, and compile. This empty document will compile without errors! Why is this possible? Why does the program compile?

Now it is time to take a quick look at the Java grammar. The reason that the program compile is that the syntax is legal! The Java Grammar say that:

CompilationUnit =
[PackageDeclaration], [ImportDeclarations], [TypeDeclarations] ;

which means that it's optional if you actually want to type anything! The rule say that a Java program could be empty. PackageDeclaration, ImportDeclarations and TypeDeclarations are optional.

Obviously, the program can't run, because there is no code. Actually, Java will complain that there's no main method: Exception in thread "main" java.lang.NoClassDefFoundError: Nothing. You should now familiarize yourself with the grammar page!

No comments: