My Home on the Web. Where the Code Snippets Run Free.

Fun with the Java main Method

Fun with the Java main Method

If you think that the main method signature could be written only one way, think again. I recently started studying for the Oracle Java Associate Programmer exam with Mala Gupta’s OCA Java SE 7 Programmer I Certification Guide: Prepare for the 1ZO-803 exam. It is an excellent book, covering a bunch of stuff traditional Java textbooks do not.

main Version 1

We’ve all seen this main signature. That’s the method signature recommended by the Java Coding conventions, and the one used in every textbook I’ve seen.

main Version 2

This main signature, though, you don’t see as often. Note that I placed the [] brackets after the parameter name. This is how you declare an array in the C language. I’m pretty sure this was added to the Java language to help C programmers transition.

main Version 3

This main signature uses the variable arguments type (varargs for short). That’s the three ..., or ellipse, to the right of the String type declaration. Unlike the first two signatures, this one lets the compiler decide if an array or single primitive String type is required based on the number of arguments received. The varargs feature automates and hides that decision process – very similar to autoboxing.
Now, this situation is a bit unique, because the varargs won’t actually allow a single command line argument to be stored in a String – it will always go to a String array. You can prove that by changing your println statement to:

You will note that the value of args is not printed, indicating the String.toString() was not called. Instead, the memory address of the String array is printed.

main Version 4

Here, I have swapped public static for static public. Still works, because public and static can be interchanged in method signatures. That said, public static is the recommended order.

main Version 5 & main Version 6

Of course, interchanging the public and static modifiers will also work for the other two versions of main above, giving you six valid ways to write the main method signature.

Only six? Did I miss any?


I intentionally skipped the idea of overriding/hiding the main method in a child

1 Comment