How do you handle command-line arguments in Java?
Table of Contents
Introduction
In Java, command-line arguments provide a way to pass data into a program at runtime. This feature allows users to influence the behavior of an application without modifying its source code. Command-line arguments are accessed via the main()
method's String[] args
parameter, where each element of the array corresponds to a space-separated argument passed during program execution.
How to Handle Command-Line Arguments
1. Accessing Command-Line Arguments
The command-line arguments are passed to the Java application when it is launched from the command line. You can access these arguments in the main()
method as follows:
Each argument provided is stored as a separate element in the args
array, with the first argument at args[0]
, the second at args[1]
, and so on. The length of the array can be checked using args.length
.
Example: Basic Command-Line Argument Handling
Here's a simple example that demonstrates how to handle and print command-line arguments in a Java application:
Running the Example
To compile and run the program, follow these steps:
-
Compile the program:
-
Execute the program with command-line arguments:
Output:
If you run the program without arguments:
Output:
2. Using Command-Line Arguments in Your Program Logic
You can use command-line arguments to affect the behavior of your application. Here’s an example that takes a filename as a command-line argument and simulates file processing:
Running the File Processor Example
-
Compile the program:
-
Run it with a filename:
Output:
Conclusion
Handling command-line arguments in Java is a straightforward process that allows you to pass user-defined inputs to your programs at runtime. By accessing the args
array in the main()
method, you can read and utilize these arguments to control your application’s behavior dynamically. This feature is essential for creating flexible and interactive Java applications.