Command Line Arguments in Java
Introduction to Command line arguments
Command line arguments are the data sent from the command prompt to a Java program
during its
execution. In a Java program, the
main() method receives these arguments using the parameter:
String[] args
public static void main(String[] args)
This means you can pass input to your program externally at runtime, without changing the code. These arguments help make your programs more dynamic, flexible, and interactive.
What is args?
- args is an array of Strings (String[] args).
- Each element in this array holds one command line argument.
- Like all arrays in Java, indexing starts from 0.
Example:
class ShikshaSanchar {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]);
}
}
Command to run in terminal / cmd:
D:/ shikshasanchar/> javac ShikshaSanchar.java
D:/ shikshasanchar/> java ShikshaSanchar Hello World
Output:
Hello
World
Explanation:
When we run the program using: java ShikshaSanchar Hello World
We are passing two arguments: "Hello" and "World". These values are stored in the args array
like
this:
| Index | Value |
|---|---|
| 0 | "Hello" |
| 1 | "World" |
- args[0] gives "Hello", so the first System.out.println() prints Hello.
- args[1] gives "World", so the second System.out.println() prints World.
Even though you didn’t ask for user input during program execution, the values were still passed through the command line and accessed using the array.
Is String[] args Mandatory in main()?
Yes, the String[] args parameter in the main() method is mandatory, even if you don’t pass any command line arguments to the program.
When you run a Java program, the Java Virtual Machine (JVM) looks for the main() method with a specific structure:
public static void main(String[] args)
This method is the starting point of your program. Even if no arguments are passed from the command line, the JVM still expects this format. The args array will simply be empty, but it must still be there.
Why is it required?
Think of it this way: Some users might run your program with input, and some might run it without input. The JVM needs to know where to store those inputs if they are provided — that's why String[] args must always be included.
Summary
- Command line arguments allow users to pass data to a Java program at runtime.
- These inputs are received in the
main()method through theString[] argsparameter. - Each argument is a string and accessed using array indexing (
args[0],args[1], etc.). - The
argsparameter is mandatory, even if no data is passed. - Command line arguments help build flexible programs without changing code every time input changes.