Java main() Method

In this chapter you will learn:

  1. What is Java main() Method
  2. What is the syntax to declare main() method
  3. How to pass command line arguments to main method

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]);
  }/*from ww w . ja  va2s .c  o  m*/
}

Try executing this program, as shown here:

When you do, you will see the following output:

Next chapter...

What you will learn in the next chapter:

  1. What is class inheritance
  2. Example - Java Class Inheritance