Home > Articles

  • Print
  • + Share This
This chapter is from the book

The main() Method

The main() method is used as the entry point for a Java application program. All application programs must have a main() method. The main() method is a method of the class that is executed to run the program.

For example, if your program's name is MyProgram, then the MyProgram class must be defined in a file named MyProgram.java. The MyProgram class must have a correctly defined main() method.

A correctly defined main() method has the following form:

public static void main(String[] args) {
 // Statements go here
}

Applets

Applets are not required to have a main() method.

The main() method must be declared as public, static, and void. The void keyword must appear immediately before main(). The public and static keywords can be interchanged. The main() method has one argument—an array of String arguments. This argument can be defined as String[] args, String []args, or String args[]. The args argument may use any valid identifier. For example, you can use arg, myArgs, or parms. However, args is standard, and you should probably stick with it. As a convention, when I refer to args, I'm referring to the argument to a program's main() method.

Know the main() Method

Make sure you master the main() method. You are likely to see more than one question about it on the exam.

The args array is used to access a program's command-line arguments. These arguments are passed to a program when it is invoked. They are passed as part of the command that is used to invoke the program.

For example, to run the MyProgram program, you would enter the following:

java MyProgram

Suppose that you wanted to pass the arguments 2 and 3 to MyProgram. You would invoke it as follows:

java MyProgram 2 3

The String object 2 would be accessed as args[0], and the String object 3 would be accessed as args[1]. If you are a C or C++ programmer—pay attention. Java accesses command-line arguments using different indices than do C and C++ programs.

The ArgsTest program of Listing 2.1 shows how command-line arguments are accessed using the args array. When you run the program using the following command line:

java ArgsTest this is a test

it displays the following results:

args[0] = this
args[1] = is
args[2] = a
args[3] = test

Listing 2.1: The ArgsTest Program

class ArgsTest {
 public static void main(String[] args) {
 for(int i=0;i<args.length;++i) {
  System.out.println("args["+i+"] = "+args[i]);
 }
 }
}
  • + Share This
  • 🔖 Save To Your Account