Command-Line Arguments
Understanding Command-Line Arguments
Command-line arguments are parameters passed to a Java program when it is launched from the terminal or command prompt. These arguments provide a way to dynamically configure program behavior without modifying the source code.
Syntax and Access
In Java, command-line arguments are received through the main
method's String[] args
parameter:
public class CommandLineDemo {
public static void main(String[] args) {
// Accessing command-line arguments
if (args.length > 0) {
System.out.println("First argument: " + args[0]);
}
}
}
Compilation and Execution
To use command-line arguments, compile and run the program as follows:
## Compile the Java file
javac CommandLineDemo.java
## Run with arguments
java CommandLineDemo Hello World
Argument Processing Workflow
graph TD
A[Compile Java Program] --> B[Run Program with Arguments]
B --> C[Arguments Passed to main method]
C --> D{Check Argument Count}
D --> |Sufficient| E[Process Arguments]
D --> |Insufficient| F[Display Usage Instructions]
Common Use Cases
Use Case |
Description |
Example |
Configuration |
Set program parameters |
java App --port 8080 |
Input Data |
Provide initial data |
java Calculator 10 20 + |
File Processing |
Specify input/output files |
java FileConverter input.txt output.txt |
Argument Type Conversion
Arguments are received as strings and need explicit conversion:
public class ArgumentConverter {
public static void main(String[] args) {
if (args.length == 2) {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println("Sum: " + (num1 + num2));
}
}
}
Best Practices
- Validate argument count and types
- Provide clear usage instructions
- Handle potential parsing exceptions
- Use meaningful argument names
LabEx Recommendation
Practice command-line argument handling in LabEx's interactive Java environments to build practical skills.