main() Method - Java Execution Entry Point

This section describes the Java program entry point, the main() method of the starting class. Command line arguments are passed as an string array parameter to the main() method.

As mentioned in the previous section, a Java application program must have a starting class with a special method call main() as the execution entry point. The main() method must be defined as follows:

   public static void main(String[] a) {
      // statement block

Note that the main() method is a class method, defined as "static". So when it is called by the JVM, no instance of the starting class will be created.

The parameter of the main() method is an array of "String", which contains the additional arguments after the class name argument in the "java" command line. Let's use the following Java program to illustrate how those arguments are passed into the main() method:

 - Copyright (c) 2014,, All Rights Reserved.
class CommandLine {
   public static void main(String[] a) {
      System.out.println("Number of arguments = "+a.length);
      for (int i=0; i<a.length; i++) {
         System.out.println("  a["+i+"] = "+a[i]);

After compiling the class, execute it with the following command line:

C:\herong>\progra~1\java\jdk1.8.0\bin\java -cp . 
   CommandLine bread milk banana apple

Number of arguments = 4
  a[0] = bread
  a[1] = milk
  a[2] = banana
  a[3] = apple

4 arguments are specified in the command line after the class name. The JVM put them in an array of 4 elements and pass the array as a parameter to the main() method.

Execute it again with a slightly different command line:

C:\herong>\progra~1\java\jdk1.8.0\bin\java -cp . 
   CommandLine "bread milk" "banana apple"

Number of arguments = 2
  a[0] = bread milk
  a[1] = banana apple

This time, double quotes are used to make two space delimited words as a single argument.

Last update: 2014.

Table of Contents

 About This Book

 Installing JDK 1.8 on Windows

Execution Process, Entry Point, Input and Output

 Creating, Compiling and Executing Java Programs

main() Method - Java Execution Entry Point

 Java Execution Console - "in", "out" and "err" Data Streams

 Primitive Data Types and Literals

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Outdated Tutorials


 PDF Printing Version