Java Command Line Arguments - Complete Tutorial
Master Java command line arguments: Learn how to pass, access, parse, validate arguments in Java programs with practical examples and best practices for runtime configuration.
Main Method Args
String[] args parameter
Argument Parsing
Advanced parsing techniques
Validation
Input validation & error handling
Real Examples
Practical use cases
1. Introduction to Java Command Line Arguments
Command line arguments in Java are parameters passed to a Java program when it's executed from the command line. These arguments allow users to configure program behavior without modifying the source code, making applications more flexible and reusable.
Why Use Command Line Arguments?
- Runtime Configuration: Change behavior without recompilation
- Automation: Scriptable program execution
- Flexibility: Support multiple use cases
- Batch Processing: Process multiple files/data sets
- Testing: Pass test parameters dynamically
- Production Control: Configure production settings
Common Use Cases
- File Processing: Specify input/output files
- Configuration: Set flags and options
- Data Parameters: Pass values for calculations
- Mode Selection: Choose program modes
- Debugging: Enable debug/logging levels
- Database Connection: Pass connection strings
How Command Line Arguments Work
Command line arguments are captured by the JVM and passed to the main method as a String[] array. Each space-separated value becomes an array element (unless enclosed in quotes).
Command Line Argument Flow
User executes: java MyProgram arg1 arg2 "arg3 with spaces"
│
▼
JVM receives command line
│
▼
JVM parses arguments into String array
│
▼
String[] args = {"arg1", "arg2", "arg3 with spaces"}
│
▼
JVM calls: MyProgram.main(args)
│
▼
Program processes args array
2. Basic Usage of Command Line Arguments
The main method signature includes a String[] args parameter that receives command line arguments. This array contains all the arguments passed to the program.
public class BasicArgsExample {
public static void main(String[] args) {
System.out.println("=== Basic Command Line Arguments Example ===");
// 1. Check if any arguments were passed
if (args.length == 0) {
System.out.println("No command line arguments provided.");
System.out.println("Usage: java BasicArgsExample [arguments]");
return;
}
// 2. Display number of arguments
System.out.println("Number of arguments: " + args.length);
// 3. Display all arguments
System.out.println("\nAll arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println(" Argument[" + i + "]: " + args[i]);
}
// 4. Access specific arguments
System.out.println("\n=== Access Specific Arguments ===");
if (args.length >= 1) {
System.out.println("First argument: " + args[0]);
}
if (args.length >= 2) {
System.out.println("Second argument: " + args[1]);
}
if (args.length >= 3) {
System.out.println("Third argument: " + args[2]);
}
// 5. Process arguments based on content
System.out.println("\n=== Processing Arguments ===");
for (String arg : args) {
if (arg.equalsIgnoreCase("--help") || arg.equals("-h")) {
System.out.println("Help: This program demonstrates command line arguments.");
} else if (arg.equalsIgnoreCase("--version") || arg.equals("-v")) {
System.out.println("Version: 1.0.0");
} else if (arg.startsWith("--file=")) {
String filename = arg.substring(7);
System.out.println("File specified: " + filename);
} else {
System.out.println("Argument: " + arg);
}
}
// 6. Example: Simple calculator with arguments
if (args.length >= 3) {
try {
double num1 = Double.parseDouble(args[0]);
String operator = args[1];
double num2 = Double.parseDouble(args[2]);
double result = 0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero!");
return;
}
break;
default:
System.out.println("Error: Invalid operator. Use +, -, *, or /");
return;
}
System.out.println("\n=== Calculation Result ===");
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format in arguments.");
}
}
}
}
| Command | args Array | args.length | Description |
|---|---|---|---|
java Program |
{} |
0 | No arguments passed |
java Program hello |
{"hello"} |
1 | Single argument |
java Program hello world |
{"hello", "world"} |
2 | Two arguments |
java Program "hello world" |
{"hello world"} |
1 | Single argument with spaces |
java Program file.txt --verbose -o output.txt |
{"file.txt", "--verbose", "-o", "output.txt"} |
4 | Mixed arguments and flags |
3. Parsing and Validating Arguments
Proper parsing and validation of command line arguments is crucial for creating robust applications. This involves checking argument count, parsing data types, and handling errors gracefully.
import java.util.HashMap;
import java.util.Map;
public class ArgumentParser {
public static void main(String[] args) {
System.out.println("=== Advanced Argument Parser ===");
if (args.length == 0) {
printUsage();
return;
}
// Parse arguments into a map for easy access
Map arguments = parseArguments(args);
// Display parsed arguments
System.out.println("\nParsed Arguments:");
for (Map.Entry entry : arguments.entrySet()) {
System.out.println(" " + entry.getKey() + " = " + entry.getValue());
}
// Validate and process arguments
processArguments(arguments);
}
private static Map parseArguments(String[] args) {
Map parsedArgs = new HashMap<>();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--")) {
// Handle --key=value format
if (arg.contains("=")) {
String[] parts = arg.split("=", 2);
if (parts.length == 2) {
parsedArgs.put(parts[0].substring(2), parts[1]);
}
}
// Handle --key value format
else if (i + 1 < args.length && !args[i + 1].startsWith("-")) {
parsedArgs.put(arg.substring(2), args[i + 1]);
i++; // Skip next argument
}
// Handle --flag (boolean flag)
else {
parsedArgs.put(arg.substring(2), "true");
}
}
else if (arg.startsWith("-")) {
// Handle -k value format
if (arg.length() == 2 && i + 1 < args.length && !args[i + 1].startsWith("-")) {
parsedArgs.put(arg.substring(1), args[i + 1]);
i++; // Skip next argument
}
// Handle -f (boolean flag)
else {
parsedArgs.put(arg.substring(1), "true");
}
}
// Handle positional arguments
else {
parsedArgs.put("positional_" + i, arg);
}
}
return parsedArgs;
}
private static void processArguments(Map args) {
System.out.println("\n=== Processing Arguments ===");
// Check for help flag
if (args.containsKey("help") || args.containsKey("h")) {
printUsage();
return;
}
// Validate required arguments
if (!args.containsKey("input")) {
System.out.println("Error: Input file is required. Use --input=filename or -i filename");
return;
}
String inputFile = args.get("input");
System.out.println("Input file: " + inputFile);
// Get output file (with default value)
String outputFile = args.getOrDefault("output", "output.txt");
System.out.println("Output file: " + outputFile);
// Check for verbose flag
boolean verbose = args.containsKey("verbose") || args.containsKey("v");
System.out.println("Verbose mode: " + verbose);
// Parse numeric parameters with validation
try {
int count = Integer.parseInt(args.getOrDefault("count", "10"));
if (count <= 0) {
System.out.println("Error: Count must be positive");
return;
}
System.out.println("Count: " + count);
} catch (NumberFormatException e) {
System.out.println("Error: Invalid count value");
return;
}
// Parse boolean flag
boolean force = args.containsKey("force") || args.containsKey("f");
System.out.println("Force mode: " + force);
// Process positional arguments
System.out.println("\nPositional arguments:");
for (int i = 0; i < 5; i++) { // Check first 5 positional arguments
String key = "positional_" + i;
if (args.containsKey(key)) {
System.out.println(" Position " + i + ": " + args.get(key));
}
}
System.out.println("\nAll arguments processed successfully!");
}
private static void printUsage() {
System.out.println("Usage: java ArgumentParser [options]");
System.out.println("\nOptions:");
System.out.println(" --help, -h Show this help message");
System.out.println(" --input=, -i Input file (required)");
System.out.println(" --output=, -o Output file (default: output.txt)");
System.out.println(" --count= Number of iterations (default: 10)");
System.out.println(" --verbose, -v Enable verbose mode");
System.out.println(" --force, -f Force operation");
System.out.println("\nExamples:");
System.out.println(" java ArgumentParser --input=data.txt --output=result.txt");
System.out.println(" java ArgumentParser -i data.txt -v -f --count=50");
}
}
- Always check
args.lengthbefore accessing elements - Provide clear error messages for missing/invalid arguments
- Include a
--helpor-hflag for documentation - Use try-catch blocks when parsing numeric arguments
- Set reasonable default values for optional arguments
- Validate file paths and permissions for file-related arguments
4. Advanced: Apache Commons CLI Library
For complex command line interfaces, Apache Commons CLI provides a robust framework for parsing and managing command line arguments with support for various option types and automatic help generation.
import org.apache.commons.cli.*;
public class CommonsCLIExample {
public static void main(String[] args) {
// Create Options object
Options options = new Options();
// Add options
options.addOption("h", "help", false, "Print this help message");
options.addOption("v", "version", false, "Print version information");
options.addOption("i", "input", true, "Input file path (required)");
options.addOption("o", "output", true, "Output file path");
options.addOption("c", "count", true, "Number of iterations");
options.addOption("f", "force", false, "Force operation without confirmation");
// Create a required option group
OptionGroup modeGroup = new OptionGroup();
modeGroup.addOption(new Option("e", "encrypt", false, "Encrypt mode"));
modeGroup.addOption(new Option("d", "decrypt", false, "Decrypt mode"));
modeGroup.setRequired(true);
options.addOptionGroup(modeGroup);
// Parse command line arguments
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println("Error: " + e.getMessage());
formatter.printHelp("CommonsCLIExample", options);
System.exit(1);
}
// Handle help option
if (cmd.hasOption("help")) {
formatter.printHelp("CommonsCLIExample", options);
System.exit(0);
}
// Handle version option
if (cmd.hasOption("version")) {
System.out.println("CommonsCLIExample v1.0.0");
System.exit(0);
}
// Process required input option
String inputFile = cmd.getOptionValue("input");
if (inputFile == null) {
System.out.println("Error: Input file is required");
formatter.printHelp("CommonsCLIExample", options);
System.exit(1);
}
System.out.println("Input file: " + inputFile);
// Process optional output option (with default)
String outputFile = cmd.getOptionValue("output", "output.txt");
System.out.println("Output file: " + outputFile);
// Process count with validation
String countStr = cmd.getOptionValue("count", "10");
try {
int count = Integer.parseInt(countStr);
if (count <= 0) {
System.out.println("Error: Count must be positive");
System.exit(1);
}
System.out.println("Count: " + count);
} catch (NumberFormatException e) {
System.out.println("Error: Invalid count value");
System.exit(1);
}
// Check boolean flags
boolean forceMode = cmd.hasOption("force");
System.out.println("Force mode: " + forceMode);
// Check mode (encrypt or decrypt)
String mode = cmd.hasOption("encrypt") ? "encrypt" : "decrypt";
System.out.println("Mode: " + mode);
// Get any remaining arguments (non-option arguments)
String[] remainingArgs = cmd.getArgs();
if (remainingArgs.length > 0) {
System.out.println("\nAdditional arguments:");
for (String arg : remainingArgs) {
System.out.println(" " + arg);
}
}
System.out.println("\nAll options processed successfully!");
}
}
| Feature | Apache Commons CLI | Manual Parsing |
|---|---|---|
| Ease of Use | High (pre-built parsing logic) | Low (manual implementation) |
| Complex Option Support | Full support (groups, required, etc.) | Manual implementation needed |
| Automatic Help | Built-in HelpFormatter | Manual implementation |
| Error Handling | Automatic validation and messages | Manual error handling |
| Dependencies | Requires commons-cli library | No dependencies |
| Best For | Complex applications with many options | Simple programs with few arguments |
5. Practical Real-World Examples
Example 1: CSV File Processor
import java.io.*;
import java.util.*;
public class CSVProcessor {
public static void main(String[] args) {
// Default values
String inputFile = null;
String outputFile = "output.csv";
String delimiter = ",";
boolean hasHeader = true;
boolean verbose = false;
// Parse command line arguments
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "-i":
case "--input":
if (i + 1 < args.length) {
inputFile = args[++i];
}
break;
case "-o":
case "--output":
if (i + 1 < args.length) {
outputFile = args[++i];
}
break;
case "-d":
case "--delimiter":
if (i + 1 < args.length) {
delimiter = args[++i];
}
break;
case "--no-header":
hasHeader = false;
break;
case "-v":
case "--verbose":
verbose = true;
break;
case "-h":
case "--help":
printHelp();
return;
default:
System.out.println("Unknown option: " + args[i]);
printHelp();
return;
}
}
// Validate required arguments
if (inputFile == null) {
System.out.println("Error: Input file is required");
printHelp();
return;
}
// Process CSV file
try {
if (verbose) {
System.out.println("Starting CSV processing...");
System.out.println("Input: " + inputFile);
System.out.println("Output: " + outputFile);
System.out.println("Delimiter: '" + delimiter + "'");
System.out.println("Has header: " + hasHeader);
}
processCSV(inputFile, outputFile, delimiter, hasHeader, verbose);
System.out.println("CSV processing completed successfully!");
} catch (IOException e) {
System.out.println("Error processing CSV: " + e.getMessage());
}
}
private static void processCSV(String inputFile, String outputFile,
String delimiter, boolean hasHeader,
boolean verbose) throws IOException {
int rowCount = 0;
int columnCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
boolean firstRow = true;
while ((line = reader.readLine()) != null) {
// Skip empty lines
if (line.trim().isEmpty()) {
continue;
}
// Process line
String[] columns = line.split(delimiter);
if (firstRow && hasHeader) {
// Process header
columnCount = columns.length;
writer.write("Processed_" + String.join("_", columns));
writer.newLine();
firstRow = false;
continue;
}
// Process data row
StringBuilder processedRow = new StringBuilder();
for (int i = 0; i < columns.length; i++) {
if (i > 0) processedRow.append(delimiter);
// Example processing: trim and uppercase
String processedValue = columns[i].trim().toUpperCase();
processedRow.append(processedValue);
}
writer.write(processedRow.toString());
writer.newLine();
rowCount++;
if (verbose && rowCount % 1000 == 0) {
System.out.println("Processed " + rowCount + " rows...");
}
}
}
if (verbose) {
System.out.println("Total rows processed: " + rowCount);
System.out.println("Columns per row: " + columnCount);
}
}
private static void printHelp() {
System.out.println("CSV Processor - Command Line Tool");
System.out.println("Usage: java CSVProcessor [options]");
System.out.println("\nOptions:");
System.out.println(" -i, --input FILE Input CSV file (required)");
System.out.println(" -o, --output FILE Output CSV file (default: output.csv)");
System.out.println(" -d, --delimiter CHAR Column delimiter (default: ,)");
System.out.println(" --no-header Input file has no header row");
System.out.println(" -v, --verbose Enable verbose output");
System.out.println(" -h, --help Show this help message");
System.out.println("\nExample:");
System.out.println(" java CSVProcessor -i data.csv -o processed.csv -d \";\" -v");
}
}
Example 2: Network Configuration Tool
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetworkConfigTool {
public static void main(String[] args) {
// Default configuration
String host = "localhost";
int port = 8080;
int timeout = 5000;
boolean ssl = false;
String protocol = "http";
// Parse arguments
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equals("--host") && i + 1 < args.length) {
host = args[++i];
} else if (arg.equals("--port") && i + 1 < args.length) {
try {
port = Integer.parseInt(args[++i]);
if (port < 1 || port > 65535) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
System.out.println("Error: Port must be between 1 and 65535");
System.exit(1);
}
} else if (arg.equals("--timeout") && i + 1 < args.length) {
try {
timeout = Integer.parseInt(args[++i]);
if (timeout < 0) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
System.out.println("Error: Timeout must be a positive number");
System.exit(1);
}
} else if (arg.equals("--ssl")) {
ssl = true;
protocol = "https";
} else if (arg.equals("--help")) {
printHelp();
System.exit(0);
} else if (arg.equals("--ping")) {
// Special command to ping host
if (i + 1 < args.length) {
String pingHost = args[++i];
pingHost(pingHost);
} else {
pingHost(host);
}
System.exit(0);
} else {
System.out.println("Unknown argument: " + arg);
printHelp();
System.exit(1);
}
}
// Display configuration
System.out.println("=== Network Configuration ===");
System.out.println("Host: " + host);
System.out.println("Port: " + port);
System.out.println("Timeout: " + timeout + "ms");
System.out.println("SSL: " + ssl);
System.out.println("Protocol: " + protocol);
System.out.println("URL: " + protocol + "://" + host + ":" + port);
// Validate host
try {
InetAddress address = InetAddress.getByName(host);
System.out.println("Host IP: " + address.getHostAddress());
System.out.println("Host reachable: " + address.isReachable(timeout));
} catch (UnknownHostException e) {
System.out.println("Error: Unknown host - " + host);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void pingHost(String host) {
System.out.println("Pinging " + host + "...");
try {
InetAddress address = InetAddress.getByName(host);
long startTime = System.currentTimeMillis();
boolean reachable = address.isReachable(5000);
long endTime = System.currentTimeMillis();
if (reachable) {
System.out.println("Host " + host + " is reachable");
System.out.println("IP Address: " + address.getHostAddress());
System.out.println("Response time: " + (endTime - startTime) + "ms");
} else {
System.out.println("Host " + host + " is not reachable");
}
} catch (Exception e) {
System.out.println("Error pinging host: " + e.getMessage());
}
}
private static void printHelp() {
System.out.println("Network Configuration Tool");
System.out.println("Usage: java NetworkConfigTool [options]");
System.out.println("\nOptions:");
System.out.println(" --host HOSTNAME Server hostname (default: localhost)");
System.out.println(" --port PORT Server port (default: 8080)");
System.out.println(" --timeout MS Connection timeout in ms (default: 5000)");
System.out.println(" --ssl Enable SSL/TLS");
System.out.println(" --ping [HOST] Ping a host (default: configured host)");
System.out.println(" --help Show this help message");
System.out.println("\nExamples:");
System.out.println(" java NetworkConfigTool --host example.com --port 443 --ssl");
System.out.println(" java NetworkConfigTool --ping google.com");
}
}
6. Best Practices and Common Mistakes
- No argument validation: Accessing args without bounds checking
- Poor error messages: Vague or technical error messages
- No help option: Forgetting to implement --help or -h
- Inconsistent naming: Mixing --long-options and -s styles randomly
- No default values: Making all arguments required
- Ignoring edge cases: Not handling quotes, spaces, special characters
Best Practices
- Always check
args.lengthbefore accessing elements - Provide clear, helpful error messages
- Implement a
--helpoption that explains usage - Use consistent naming conventions for options
- Set sensible default values for optional arguments
- Validate and sanitize all user input
- Use libraries (like Apache Commons CLI) for complex interfaces
Pro Tips
- Support both
--long-optionand-sshort forms - Use
=for parameter assignment:--file=data.txt - Group related options together in help output
- Consider using environment variables as fallbacks
- Document your command line interface thoroughly
- Test with various argument combinations
- Handle
Ctrl+Cgracefully
When to Use Command Line Arguments
Use command line arguments when: You need runtime configuration, automation, or scripting support
Consider alternatives when: Configuration is complex (use config files), needs GUI (use Swing/JavaFX), or requires user interaction during runtime
Command Line Argument Decision Flow
Start Program Design
│
▼
Does program need runtime configuration?
│
├── No ───▶ Use hardcoded values or properties file
│
▼
Yes
│
▼
Will configuration be changed frequently?
│
├── No ───▶ Consider environment variables
│
▼
Yes
│
▼
How many parameters are needed?
│
├── 1-3 ───▶ Simple command line arguments
│
├── 4-10 ──▶ Structured arguments with validation
│
└── 10+ ───▶ Use Apache Commons CLI or similar library
│
▼
Always implement --help and proper validation