How to declare main method for Java program

Description

The main() method is the entry point for standalone Java applications. To create an application, you write a class definition that includes a main() method. To execute an application, type java at the command line, followed by the name of the class containing the main() method.

Syntax for main() method

The signature for main() is:


public static void main(String[] args)

The return type must be void. The main() method must be public. It is static so that it can be executed without constructing an instance of the application class.

Example

A command-line argument is the information that follows the program's name on the command line. The command-line arguments are stored as string array passed to main(). For example, the following program displays all of the command-line arguments:

 
public class Main {
  public static void main(String args[]) {
    for (int i = 0; i < args.length; i++)
      System.out.println("args[" + i + "]: " + args[i]);
  }// w  w  w. j  ava2s  .c  om
}

Try executing this program, as shown here:

When you do, you will see the following output:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures