The Main() Conspiracy

Typical Java

I was browsing StackOverflow this evening when I came across this question. The question itself isn't anything special, but the quote from the Thread JavaDoc caught my eye:

"When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class)."

"Typically" calls main()? I mean, sure, you could call java SomeClassWithoutAMainMethod and the JVM would start up, cough, and die. But that hardly seems worth a parenthetical shout out in the JavaDocs, right? There's got to be more to it than that.

Static Initialization

So, how can we write a Java program that runs without a main() method ever being called? We'll need code that exists outside of a named method that we can get to run before the JVM discovers the main method is missing. What happens before main() is called? The class that is supposed to contain main() gets loaded. And how do you run code when a class is loaded? Static initialization!

public class Mainless {
        static {
                System.out.println("Mainless!");
                System.exit(0);
        }
}

And there you have it: a Java program with no main() method. The static initialization block runs when the Mainless class is loaded, before the JVM tries to call main (which, you'll note, doesn't exist). "But wait," you say, "I was taught in Java 101 that every program has a main() method!" And like much of what we learn in school, that isn't strictly true. Why the conspiracy to keep Java developers writing public static void main(String[] args)? Well, it does have practical uses. For example, you can't pass arguments to the static initialization block. You could set environment variables before running Mainless and access those variables, but that's just ugly. And, you have to call System.exit() at some point or you'll get an error message about the missing main() method.

The big question: why?

But, is there any point to this? Not as far as I can tell. There's no practical use of this technique that I know of. You save a little bit of typing and get an obscure piece of code that might confuse a lot of Java developers. And I'm sure somebody, somewhere, uses this fact in an obnoxious "gotcha" interview question. I hate those.

No comments:

Post a Comment