Command Line Arguments in Java
What are Command Line Arguments?
Command Line Arguments are inputs you can give to your Java program from the terminal (Command Prompt, Bash, etc.) when running the program.
These arguments are passed to the program’s main()
method using this syntax: public static void main(String[] args)
. Here, String[] args
is an array of strings that stores command-line inputs.
Use Cases:
- Accept user input without GUI or Scanner
- Configure program behavior from outside (e.g., filename, settings, flags)
Each space-separated word you type after the class name becomes an element in the args
array.
Example Using Loop:
public class CommandLineExample {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
Output:
If run with: java CommandLineExample Apple Banana
The output will be:
Argument 0: Apple
Argument 1: Banana
Example Without Loop:
public class CommandLineExample {
public static void main(String[] args) {
if (args.length >= 2) {
System.out.println("Argument 0: " + args[0]);
System.out.println("Argument 1: " + args[1]);
} else {
System.out.println("Please provide at least 2 arguments.");
}
}
}
Output:
If run with: java CommandLineExample Hello World
Output:
Argument 0: Hello
Argument 1: World
How to compile and run:
// Save the file as CommandLineExample.java javac CommandLineExample.java java CommandLineExample Hello World
NOTE: If you don’t pass enough arguments (like only one), you'll get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException