The Anatomy of a Java Application |
A Java application (likeimport java.util.Date; class DateApp { public static void main(String args[]) { Date today = new Date(); System.out.println(today); } }DateApp
in the code listed above) must contain amain()
method whose signature looks like thisThe method signature for thepublic static void main(String args[])main()
method contains three modifiers:The
public
indicates that themain()
method can be called by any object. Missing Page covers the ins and outs of access modifiers supported by the Java language: public, private, protected, and the implicit, friendly.static
indicates that themain()
method is a static method (also known as class method). Static vs. Instance later in this lesson talks in more detail about static methods and variables.void
indicates that themain()
method has no return value.main()
method in the Java language is similar to themain()
function in C and C++. When you execute a C or C++ program, the runtime system starts your program by calling itsmain()
function first. Themain()
function then calls all the other functions required to run your program. Similarly, in the Java language, when you execute a class with the Java interpreter, the runtime system starts by calling the class'smain()
method. Themain()
method then calls all the other methods required to run your application.If you try to run a class with the Java interpreter that does not have a
main()
method, the interpreter prints an error message. For more information see Troubleshooting Interpreter Problems .Arguments to the main() Method
As you can see from the code snippet above, themain()
method accepts a single argument: an array of Strings.This array of Strings is the mechanism through which the runtime system passes information to your application. Each String in the array is called a command line argument. Command line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command line argument:public static void main(String args[])-descendingThe
DateApp
application ignores its command line arguments, so there's isn't much more to discuss here. However, you can get more information about command line arguments, including the framework for a command line parser that you can modify for your specific needs in the Command Line Arguments lesson.
Note to C and C++ Programmers: The number and type of arguments passed to themain()
method in the Java runtime environment differ from the number and type of arguments passed to C and C++'smain()
function. For further information refer to Java Command Line Arguments Differ from C and C++ .
The Anatomy of a Java Application |