Exploring the Main Method in Java
What is the main method?
The main method is the entry point for any Java program. When you run a Java application, the Java Virtual Machine (JVM) looks for the main method to begin the execution of the program.
The signature of the main method:
public static void main(String[] args)
Components of main method:
- public
- static
- void
- main
- String[] args
- public : The public keyword means that the main method can be accessed from anywhere. Since it's the entry point of the program, it needs to be accessible by the JVM, which is why it’s defined as public.
- static : The static keyword means that the main method belongs to the class itself, not to an instance of the class. This allows the JVM to call the main method without creating an object of the class first.
- void : The void keyword means that the main method does not return any value. The JVM does not expect any value to be returned from the main method.
- main : main is the name of the method. This is the standard name recognized by the JVM as the starting point of the program.
- String[] args :
- This is a parameter that accepts command-line arguments. It's an array of Strings (String[]), and args is the variable name representing that array. When you run a Java program, you can pass values from the command line (like flags or data), which will be stored in this array.
- For example, if you run your Java program as:
java MyProgram Shiksha Sanchar
The args array will contain:
- args[0] = " Shiksha "
- args[1] = " Sanchar "
Java Program: Command Line Arguments Example
This program shows how to print command-line arguments in Java
using
args[] inside the main() method.
Source Code:
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println(args[0]);
System.out.println(args[1]);
}
}
Terminal Commands:
D:/shikshasanchar/> javac MyProgram.java
D:/shikshasanchar/> java MyProgram Shiksha Sanchar
Output:
Hello, World!
Shiksha
Sanchar
Explanation:
System.out.println("Hello, World!");— This prints a welcome message.args[0]— Refers to the first command-line argument ("Shiksha").args[1]— Refers to the second command-line argument ("Sanchar").
Why is the main method important?
-
It serves as the starting point of any Java application.
-
The JVM needs to know where to begin execution, and the main method provides that entry point.
Summary:
- public static void main(String[] args) is the mandatory signature for the main method in Java.
- It allows the program to run and pass any command-line arguments to the program.