Java Programming
Command Line
Study Guide
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.
How Java Handles Command Line Arguments
- Arguments are passed to the
main()method as aStringarray - The parameter is conventionally named
args(but can be any valid name) - Arguments are separated by spaces
- Arguments are accessed using array indices
Basic Example
CommandLineExample.java
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
// Print all arguments
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
Compile and run:
Terminal
javac CommandLineExample.java
java CommandLineExample Hello World 123
Output:
Output
Number of arguments: 3
Argument 0: Hello
Argument 1: World
Argument 2: 123
Different Ways to Access Arguments
1. Using Index
IndexExample.java
public class IndexExample {
public static void main(String[] args) {
if (args.length > 0) {
String first = args[0];
String second = args[1];
System.out.println("First: " + first);
System.out.println("Second: " + second);
}
}
}
2. Using Enhanced For Loop
ForEachExample.java
public class ForEachExample {
public static void main(String[] args) {
System.out.println("All arguments:");
for (String arg : args) {
System.out.println(arg);
}
}
}
3. Converting to Different Data Types
TypeConversionExample.java
public class TypeConversionExample {
public static void main(String[] args) {
if (args.length >= 3) {
// Convert to integer
int number = Integer.parseInt(args[0]);
// Convert to double
double decimal = Double.parseDouble(args[1]);
// Convert to boolean
boolean flag = Boolean.parseBoolean(args[2]);
System.out.println("Integer: " + number);
System.out.println("Double: " + decimal);
System.out.println("Boolean: " + flag);
}
}
}
Run:
Terminal
java TypeConversionExample 42 3.14 true
Practical Examples
Example 1: Calculator Program
Calculator.java
public class Calculator {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: java Calculator <num1> <operator> <num2>");
System.out.println("Example: java Calculator 10 + 5");
return;
}
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(num1 + " " + operator + " " + num2 + " = " + result);
} catch (NumberFormatException e) {
System.out.println("Error: Please enter valid numbers");
}
}
}
Usage:
Terminal
java Calculator 10 + 5 # Output: 10.0 + 5.0 = 15.0
java Calculator 20 / 4 # Output: 20.0 / 4.0 = 5.0
Example 2: File Processor
FileProcessor.java
import java.io.*;
import java.nio.file.*;
public class FileProcessor {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java FileProcessor <filename> [operation]");
System.out.println("Operations: read, info (default: info)");
return;
}
String filename = args[0];
String operation = args.length > 1 ? args[1] : "info";
File file = new File(filename);
if (!file.exists()) {
System.out.println("Error: File '" + filename + "' not found");
return;
}
switch (operation.toLowerCase()) {
case "read":
readFile(file);
break;
case "info":
showFileInfo(file);
break;
default:
System.out.println("Unknown operation: " + operation);
}
}
private static void readFile(File file) {
try {
System.out.println("Contents of " + file.getName() + ":");
System.out.println("------------------------");
Files.lines(file.toPath()).forEach(System.out::println);
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
private static void showFileInfo(File file) {
System.out.println("File Information:");
System.out.println("Name: " + file.getName());
System.out.println("Path: " + file.getAbsolutePath());
System.out.println("Size: " + file.length() + " bytes");
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
}
}
Example 3: User Greeting with Options
GreetingApp.java
public class GreetingApp {
public static void main(String[] args) {
// Default values
String name = "User";
String greeting = "Hello";
boolean uppercase = false;
// Parse command line arguments
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "-n":
case "--name":
if (i + 1 < args.length) {
name = args[++i];
}
break;
case "-g":
case "--greeting":
if (i + 1 < args.length) {
greeting = args[++i];
}
break;
case "-u":
case "--uppercase":
uppercase = true;
break;
case "-h":
case "--help":
printHelp();
return;
default:
System.out.println("Unknown option: " + args[i]);
printHelp();
return;
}
}
String message = greeting + ", " + name + "!";
if (uppercase) {
message = message.toUpperCase();
}
System.out.println(message);
}
private static void printHelp() {
System.out.println("Greeting App Usage:");
System.out.println(" java GreetingApp [options]");
System.out.println("Options:");
System.out.println(" -n, --name <name> Set your name");
System.out.println(" -g, --greeting <msg> Set greeting message");
System.out.println(" -u, --uppercase Display in uppercase");
System.out.println(" -h, --help Show this help");
System.out.println("\nExample:");
System.out.println(" java GreetingApp -n John -g Hi -u");
}
}
Usage examples:
Terminal
java GreetingApp -n Alice -g Welcome
java GreetingApp --name Bob --uppercase
java GreetingApp -h
Handling Spaces and Special Characters
Arguments with Spaces
Use double quotes for arguments containing spaces:
Terminal
java Program "Hello World" "Multiple words here"
SpacesExample.java
public class SpacesExample {
public static void main(String[] args) {
for (String arg : args) {
System.out.println("Arg: " + arg);
}
}
}
Escape Characters
Terminal
# Using quotes
java Program "He said \"Hello\""
# Using escape in Unix/Linux
java Program He\ said\ Hello
Common Errors and Solutions
| Error | Cause | Solution |
|---|---|---|
ArrayIndexOutOfBoundsException |
Accessing non-existent argument | Check args.length first |
NumberFormatException |
Invalid number conversion | Use try-catch blocks |
| Missing arguments | User didn't provide required args | Provide clear usage instructions |
| Spaces in arguments | Arguments with spaces not quoted | Use quotes around arguments |
Debugging Tips
DebugArgs.java
public class DebugArgs {
public static void main(String[] args) {
// Debug: Print all arguments
System.out.println("Debug: Received " + args.length + " arguments");
for (int i = 0; i < args.length; i++) {
System.out.println(" args[" + i + "] = \"" + args[i] + "\"");
}
// Your main logic here
}
}
Quick Reference Card
Command Line Quick Reference
# Compile
javac ProgramName.java
# Run with arguments
java ProgramName arg1 arg2 arg3
# Run with quoted arguments
java ProgramName "argument with spaces" arg2
# Access in code
String first = args[0];
int number = Integer.parseInt(args[1]);
double value = Double.parseDouble(args[2]);
# Check length
if (args.length > 0) { ... }
# Loop through
for (String arg : args) { ... }