- Back to Home »
- Java Main Program
A Java program needs to start its execution somewhere. It does so in a static method of a class. This method must be named
main()
and take an array of String
's as parameter. Don't worry about the concepts of classes, methods and parameters for now. They will all be explained in later texts.
When you start a Java program you usually do so via the command line (console). You call the
java
command that comes with the JRE, and tells it what Java class to execute, and what arguments to pass to the main()
method. The Java application is then executed inside the JVM (orby the JVM some would claim). Here is a diagram illustrating this:A command line executing the java command, which in turn executes a Java main program. |
Here is an example command line:
java MyProgram param1 param2 param3
The first part of this command is the
java
command. This command starts up the JVM. The second argument is the name of the Java class the JVM is to execute. The last three arguments are parameters to the program. These arguments are what are present in the String
array of themain()
method, when the main()
is executed by the JVM.
Here is an example Java class with a
main()
method which can be executed by the JVM:public class MyProgram { public static void main(String[] args) { System.out.println("Hello World, Java Program"); } }
This example shows a class called
MyProgram
with a static
method in called main()
. It is themain()
method that is executed when the program is started. Whatever code is inside the main()
method is what gets executed. In the example above it is the statement:System.out.println("Hello World, Java Program");
The
main()
method takes an array of String
's as parameters. The parameters are provided to the program from the command line when it is executed.