Java main() Method
In this chapter you will learn:
- What is Java main() Method
- What is the syntax to declare main() method
- How to pass command line arguments to main method
Description
The main()
method is the entry point for standalone Java applications.
To create an application, you write a class definition that includes a main()
method.
To execute an application, type java at the command line, followed by the name
of the class containing the main()
method.
Syntax for main() method
The signature for main() is:
public static void main(String[] args)
The return type must be void
.
The main() method must be public
.
It is static so that it can be executed without constructing
an instance of the application class.
Example
A command-line argument is the information that follows the program's name on the command line. The command-line arguments are stored as string array passed to main(). For example, the following program displays all of the command-line arguments:
public class Main {
public static void main(String args[]) {
for (int i = 0; i < args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}/*from ww w . ja va2s .c o m*/
}
Try executing this program, as shown here:
When you do, you will see the following output:
Next chapter...
What you will learn in the next chapter:
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class InheritanceJava super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files