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 main class with a special method call main() as the execution entry point. The main() method must be defined as:

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

Note that the main() method must be declared as "public static void".

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) 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:

herong> javac

herong> java -classpath . 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:

herong> java -classpath . 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.

Table of Contents

 About This Book

 JDK - Java Development Kit

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

 Control Flow Statements

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 Enum Types and Enum Constants

 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

 Java Modules - Java Package Aggregation

 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

 Assert Statements and -ea" Option

 Annotation Statements and Declarations

 Java Related Terminologies

 Archived Tutorials


 Full Version in PDF/EPUB