Java Fundamentals  «Prev  Next»


Lesson 4 The main() method
Objective Main() method as an entry point

Java main() method

Use of the main() method as an entry point.

The main() method is the entry point for a Java program.
It is the first method that is invoked when a Java program is run.
A correctly defined main() method has the following signature: [1]
  1. Naming context :A context or scope in which identifiers are unique.
main method on the exam
public static void main(String[] args) {
 // The statements of the method are put here.
}

The modifiers[2] public and static , and the void return type must precede the main() method name. The main() method has a single argument that is an array of String objects. The args identifier is used by custom as the argument name. However, any other valid identifier may be used in place of args .

Only Java application programs need a main() method. Applets are not required to have a main() method since they are executed by browsers within the context of a Web page. The argument of the main() method provides access to the program's command line arguments. For example, suppose that a program is invoked with command line arguments of abc , def , and ghi. Then args[0] would reference the String "abc" , args[1] would reference "def", and args[2] would reference "ghi" . The MainTest program provides an example of using the main() method to access command line arguments.

Main method

The first requirement in creating an executable Java application is to create a class with a method whose signature (name and method arguments) match the main method, defined as follows:

public class HelloExam {
 public static void main(String args[]) {
  System.out.println("Hello exam");
 }
}
This main method should comply with the following rules:
  1. The method must be marked as a public method.
  2. The method must be marked as a static method.
  3. The name of the method must be main.
  4. The return type of this method must be void.
  5. The method must accept a method argument of a String array or a variable argument of type String.

[1]Signature: The name of the method and the number and types of formal parameters to the method.
[2]Modifier: A keyword that is used to modify the definition of a class, variable, method, or constructor.

SEMrush Software