Previous | Next | Trail Map | Getting Started | The "Hello World" Application


The main() Method

class HelloWorldApp {
    public static void main (String args[]) {
        System.out.println("Hello World!");
    }
}
Every Java application must contain a main() method whose signature looks like this:
public static void main(String args[])
The method signature for the main() method contains three modifiers:

How the main() Method Gets Called

The main() method in the Java language is similar to the main() function in C and C++. When you execute a C or C++ program, the runtime system starts your program by calling its main() function first. The main() function then calls all the other functions required to run your program.

Similarly, when the Java interpreter executes a application (by being invoked upon the application's controlling class), it starts by calling the class's main() method. The main() method then calls all the other methods required to run your application.

If you try to run the Java interpreter on a class that does not have a main() method, the interpreter displays an error message similar to this one and refuses to compile your program:

In class classname: void main(String argv[]) is not defined
where classname is the name of the class that you tried to run

Arguments to the main() Method

As you can see from the following code snippet, the main() method accepts a single argument: an array of Strings.
public static void main(String args[])
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:
-descending
The "Hello World" application ignores its command-line arguments, so there 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 Setting Program Attributes(in the Writing Java Programs trail)lesson.


Note to C and C++ Programmers: The number and type of arguments passed to the main() method in the Java runtime environment differ from the number and type of arguments passed to C and C++'s main() function. For further information refer to Command Line Arguments(in the Writing Java Programs trail)in the Setting Program Attributes lesson.


Previous | Next | Trail Map | Getting Started | The "Hello World" Application