Command-line arguments in Java allow us to pass information to a program during its execution. These arguments are passed directly from the command line and can be used by the program as needed.
Basic Example: Command-Line Arguments
Consider the following Java program:
class Main {
public static void main(String[] args) {
System.out.println("Command-Line arguments are:");
// Loop through all arguments
for (String str : args) {
System.out.println(str);
}
}
}
How to Compile and Run the Program
To compile the program, use the following command:
javac Main.java
To run the program without any arguments:
java Main
If you want to pass arguments to the program, you can append them after the class name. For example:
java Main apple ball cat
In this case, apple, ball, and cat are the command-line arguments. The program will output:
Command-Line arguments are:
apple
ball
cat
How It Works
In the program above, the main() method takes an array of strings args as its parameter:
public static void main(String[] args) {
This array stores all the arguments passed from the command line. Note that arguments are always passed as strings, and they are separated by spaces.
Passing Numeric Command-Line Arguments
Since the main() method only accepts string arguments, numeric values cannot be directly passed as numbers. However, they can be converted from strings to numeric types later in the program.
Example: Numeric Command-Line Arguments
Here’s a program that accepts numeric values as command-line arguments and converts them to integers:
class Main {
public static void main(String[] args) {
for (String str : args) {
// Convert the string argument into an integer
int argument = Integer.parseInt(str);
System.out.println("Argument in integer form: " + argument);
}
}
}
Running the Program
To run the program with numeric arguments:
java Main 11 23
The output will be:
Argument in integer form:
11
23
How the Conversion Works
In this example, the following line of code converts the string argument into an integer:
int argument = Integer.parseInt(str);
Here, Integer.parseInt() is used to convert a string to an integer. Similarly, you can use Double.parseDouble() or Float.parseFloat() to convert strings to double or float values.
Summary
•Java command-line arguments allow you to pass data to your program during execution.
•These arguments are passed as strings and can be converted to numeric types using methods like Integer.parseInt().
•You can compile the program with javac and pass arguments during execution with the java command.
This flexible approach enables you to provide input dynamically, making your Java programs more interactive and adaptable to different scenarios.