Command Line Arguments in Java Explained
Command Line Arguments
Command line arguments provide a mechanism to pass data to a Java program at the time of execution, rather than hardcoding values or requesting interactive input. They enable programs to behave dynamically based on external input and are widely used in automation scripts, backend services, build tools, and production deployments.
In Java, command line arguments are handled through the main method and are available to the program before execution begins.
Purpose of Command Line Arguments
Command line arguments are used to:
- Configure program behavior at runtime
- Pass input without user interaction
- Automate program execution
- Control application settings
- Enable reusable and flexible programs
They are especially useful in environments where programs are executed via scripts, schedulers, or CI/CD pipelines.
🔷 Command Line Arguments in Java
🔹 Program Entry Point
Every Java application starts execution from the main method:
public static void main(String[] args)
Here:
argsis a String array- It stores values passed from the command line
- These values are available at program startup
🔹 Key Characteristics of args
argsis never nullargs.lengthdepends on the number of inputs provided- All command line inputs are treated as String
- Indexing starts from 0
Even numeric values like 10 or 20 are received as strings.
🔹 Passing Command Line Arguments
Step 1: Compilation
javac Program.java
Step 2: Execution with Arguments
java Program value1 value2 value3
Each space-separated value becomes one element in the args array.
🔹 Basic Example: Accessing Arguments
Code
class CommandLineDemo {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]);
}
}
Execution
java CommandLineDemo Java Programming
Output
Java
Programming
🔹 How Java Stores These Values
Command executed:
java Test 10 20 30
Internally:
args[0] → "10"
args[1] → "20"
args[2] → "30"
Array size:
args.length == 3
This mapping is automatic and handled by the JVM.
🔹 Iterating Over Command Line Arguments
Using Traditional for Loop
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
Execution
java Test A B C
Output
A
B
C
Using Enhanced for Loop
for (String value : args) {
System.out.println(value);
}
Output (same input)
A
B
C
Both approaches are correct.
Choose based on whether index access is required.
🔹 Type Conversion of Arguments (Critical Concept)
Command line arguments are always strings.
Explicit conversion is required for numeric or logical operations.
🔸 String → int
int number = Integer.parseInt(args[0]);
🔸 String → double
double price = Double.parseDouble(args[1]);
🔸 String → boolean
boolean status = Boolean.parseBoolean(args[2]);
Accepted boolean values:
"true"→true- Anything else →
false
⚠️ Conversion Failure
If input cannot be converted:
Integer.parseInt("abc");
Result:
NumberFormatException
This is a runtime exception.
🔹 Complete Example with Type Conversion
Code
class Calculator {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
Execution
java Calculator 10 20
Output
Sum = 30
🔹 Validating Command Line Arguments (Best Practice)
Checking Argument Count
if (args.length < 2) {
System.out.println("Please provide two numbers");
return;
}
Prevents:
ArrayIndexOutOfBoundsException
Handling Invalid Input
try {
int value = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("Invalid number format");
}
Prevents:
- Program crash
- Unexpected termination
🔹 Default Values for Missing Arguments
Very common in real applications (servers, tools, utilities).
Example
int port = 8080;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
System.out.println("Running on port: " + port);
Execution
java Server
Output:
Running on port: 8080
java Server 9090
Output:
Running on port: 9090
🔹 Execution Flow Summary
- JVM starts the program
main(String[] args)is called- Command line values populate
args - Program logic processes them
- Conversion + validation ensures safety
Command Line Arguments vs User Input
| Aspect | Command Line Arguments | User Input |
|---|---|---|
| Input Time | Program start | Runtime |
| Interaction | Non-interactive | Interactive |
| Automation | High | Low |
| Use Case | Configuration | User-driven logic |
Common Errors and Pitfalls
- Accessing arguments without checking length
- Forgetting type conversion
- Assuming numeric input
- Ignoring invalid formats
- Hardcoding argument positions without documentation
Such mistakes often cause runtime failures.
Use Cases in Professional Applications
Command line arguments are commonly used for:
- Application configuration (port, environment, mode)
- Batch processing
- Automation scripts
- Test execution parameters
- Build and deployment tools
They allow programs to remain flexible without code changes.
Best Practices
- Always validate argument count
- Handle parsing exceptions
- Document expected arguments clearly
- Use meaningful argument order
- Provide default values where possible
These practices improve reliability and usability.
Limitations of Command Line Arguments
- Suitable only for small input sets
- Not secure for sensitive data
- Fixed at program start
- All input treated as strings
For complex input, configuration files or environment variables are preferred.
Command Line Arguments in IDEs
Most IDEs allow specifying arguments:
- Run Configuration settings
- Arguments entered as space-separated values
- Useful for testing without terminal execution
This ensures consistency between development and deployment.
Takeaway
- Command line arguments enable dynamic program behavior
- They are processed before program execution
- Always validate and convert explicitly
- Essential for:
- Utilities
- Build tools
- Server configurations
- Automation scripts
Conclusion
Command line arguments allow Java programs to receive input at execution time, enabling dynamic behavior without modifying source code. They are passed as a string array to the main method and require explicit validation and type conversion. Proper use of command line arguments improves automation, configurability, and deployment flexibility. Mastery of this concept is essential for developing production-ready Java applications.