Command line arguments allow users to pass additional information to a program at runtime. In Java, these arguments are passed as an array of strings to the main method of a class.
For example, consider the following program that prints the output of the sum of two numbers:
public class Main {
public static void main(String[] args) {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}
To run this program and pass in the two numbers, we can use the following command:
java Main 10 20
This will output “Sum: 30” to the console.
It’s important to note that the indices of the args
array corresponds to the position of the arguments on the command line. In this example, args[0]
is "10"
and args[1]
is "20"
.
We can also use command line arguments to pass in additional options or flags to a program. For example, we might have a program that takes a -v
flag to enable verbose mode. In this case, we could use the following command to run the program in verbose mode:
java Main -v
To check for the presence of a flag in the args
array, we can use an if
statement:
if (args[0].equals("-v")) {
// Enable verbose mode
}
Command line arguments in Java can be a powerful tool for customizing the behavior of a program at runtime. Whether we are looking to pass in data, enable certain features, or just give users additional flexibility, they’re worth considering as part of your Java development toolkit.