The main Method | Overview of Java Language

The main Method

The first bold line in the following listing begins the definition of a main method.

/**
* The HelloWorldApp class implements an application that
* simply displays “Hello World!” to the standard output.
*/

class HelloWorldApp {
public static void main(String[] args)
{
System.out.println(“Hello World!”); //Display the string.
}
}

Every Java application must contain a main method whose signature looks like this:

public static void main(String[] args)
{
System.out.println(“Hello World!”); //Display the string.
}
}

 

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:

• public indicates that the main method can be called by any object.
• static indicates that the main method is a class method.
• void indicates that the main method doesn’t return any value.

How the main Method Gets Called
The main method in the Java language is similar to the main function in C and C++. When the Java interpreter executes an 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 invoke the Java interpreter on a class that does not have a main method, the interpreter refuses to compile your program and displays an error message similar to this: In class NoMain: void main(String argv[]) is not defined

Arguments to the main Method
Here the main method accepts a single argument: an array of elements of type String.
public static void main(String[] args)

This array is the mechanism through which the runtime system passes information to your application. Each String in the array is called a command-line argument.