Command-Line Arguments
When you run a Java program, you can pass extra information directly from the terminal. These values — called command-line arguments — let you customize your program’s behavior without changing the source code.
What Are Command-Line Arguments?
Every Java program starts with the main method:
public static void main(String[] args)
The args parameter is a String array. When you run your program from the terminal, any space-separated values you type after the class name get loaded into this array automatically by the JVM.
For example, if you run:
java MyApp Alice 30
Then args[0] is "Alice" and args[1] is "30".
Note: Arguments are always received as
Stringvalues, even if you type a number. You’ll need to convert them yourself if you need a different type.
Your First Example
public class Greet {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Hello, World!");
} else {
System.out.println("Hello, " + args[0] + "!");
}
}
}
Compile and run:
javac Greet.java
java Greet Alice
Output:
Hello, Alice!
Run it without any arguments:
java Greet
Output:
Hello, World!
Reading Multiple Arguments
args is just a regular array, so you can loop over it like any other array.
public class PrintArgs {
public static void main(String[] args) {
System.out.println("You passed " + args.length + " argument(s):");
for (int i = 0; i < args.length; i++) {
System.out.println(" args[" + i + "] = " + args[i]);
}
}
}
java PrintArgs apple banana cherry
Output:
You passed 3 argument(s):
args[0] = apple
args[1] = banana
args[2] = cherry
Tip: Use the for-each loop if you only need the values and not the index:
for (String arg : args) { ... }
Converting Arguments to Other Types
Since arguments arrive as strings, use the Wrapper Classes to parse them into numbers or booleans.
public class Calculator {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java Calculator <num1> <num2>");
return;
}
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("Sum: " + (a + b));
System.out.println("Product: " + (a * b));
}
}
java Calculator 6 7
Output:
Sum: 13
Product: 42
Common parsing methods:
| Target Type | Method |
|---|---|
int | Integer.parseInt(args[0]) |
long | Long.parseLong(args[0]) |
double | Double.parseDouble(args[0]) |
boolean | Boolean.parseBoolean(args[0]) |
Warning: If the user passes a non-numeric string where you expect a number,
parseIntthrows aNumberFormatException. Always validate or wrap your parsing in a try-catch — see Exception Handling.
Handling Spaces in Arguments
If a single argument contains a space, wrap it in double quotes when running from the terminal:
java Greet "John Doe"
The entire "John Doe" is treated as one argument and lands in args[0].
Passing Arguments in an IDE
If you’re using an IDE like IntelliJ IDEA or Eclipse, you don’t need the terminal:
- IntelliJ IDEA: Run > Edit Configurations > Program arguments field
- Eclipse: Run > Run Configurations > Arguments tab > Program arguments field
Type your arguments there just as you would in the terminal (without the class name).
Validating Arguments
It’s good practice to check args.length before accessing any index to avoid an ArrayIndexOutOfBoundsException.
public class Divide {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Error: Expected exactly 2 arguments.");
System.err.println("Usage: java Divide <dividend> <divisor>");
System.exit(1); // non-zero exit signals an error to the shell
}
double dividend = Double.parseDouble(args[0]);
double divisor = Double.parseDouble(args[1]);
if (divisor == 0) {
System.err.println("Error: Cannot divide by zero.");
System.exit(1);
}
System.out.printf("%.2f / %.2f = %.2f%n", dividend, divisor, dividend / divisor);
}
}
java Divide 10 4
Output:
10.00 / 4.00 = 2.50
Tip:
System.errprints to the standard error stream, which is separate from standard output. This makes it easy to redirect only errors in shell scripts.
Real-World Use Cases
Command-line arguments shine whenever you want one binary to serve many purposes:
- File processors:
java Converter input.csv output.json - Configuration:
java Server --port 8080 --host localhost - Batch jobs: pass a date range or record IDs to process
- Testing: toggle debug/verbose mode without recompiling
For more complex CLIs with named flags (like --port), consider a library like Apache Commons CLI or picocli — but for simple programs, plain args is perfectly fine.
Under the Hood
When the JVM launches main, it constructs the args array from the OS-level argument vector (argv in C terms), skipping argv[0] (the program name itself). The array is created on the heap as an ordinary String[] object with length equal to the number of arguments provided. If no arguments are given, args is an empty array (args.length == 0), never null, so you can safely call args.length without a null check.
Each String in the array is a distinct heap object backed by the platform’s default charset decoding of the raw bytes the shell passed. On modern systems this is UTF-8, so Unicode arguments generally work fine.
System.exit(int) triggers the JVM shutdown sequence — it runs registered Shutdown Hooks and then terminates the process with the given exit code. A code of 0 means success; anything else signals failure to the calling shell or CI system.
Related Topics
- Variables — store and work with the values you parse from args
- Wrapper Classes — convert String arguments into int, double, and other types
- Arrays — understand how the
String[] argsarray works - Exception Handling — gracefully handle bad input with try-catch
- Shutdown Hook — run cleanup code when your CLI program exits
- Methods — learn how
mainfits into the broader method model