Syntax of a main Method

Each entry point of a Java program should be defined as follows:

          public static void main (String[] args) {
              ...
          }

The argument passed to main, conventionally called args, is an array of strings representing the arguments that were passed to the program on the command line. Those arguments provide a convenient way to supply simple inputs to a Java program.

Example: Suppose we run a Java program by saying

      java Class1 20 hello there

Then the args array passed to the static main method of class Class1 will be of length 3, and its elements will be the strings "20" "hello" "there".

Example: The following main method just prints its command-line arguments and then exits:

          public static void main (String[] args) {
              for (String arg : args) {
                  System.out.println (arg);
              }
          }

(The for syntax of that example is called a for-each loop because it was inspired by the for-each procedure of Scheme, which is similar to Scheme's map function except it doesn't return a useful result. Java's for-each loops are useful only when their bodies have a side effect (such as printing).