Command line arguments in Java 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
Output:
Sum: 30
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.
Frequently Asked Questions
What are command-line arguments in Java?
Command-line arguments are values passed to a Java program when it is executed from the command line, providing input or configuration options.
How do I access command-line arguments in a Java program?
Command-line arguments are stored as strings in the args
parameter of the main
method. You can access them by indexing args
(e.g., args[0]
for the first argument).
How do I run a Java program with command-line arguments?
To run a Java program with command-line arguments, use the java
command followed by the program’s class name and the arguments, like this: java MyProgram arg1 arg2
.
Can I pass different data types as command-line arguments in Java?
Command-line arguments are always passed as strings. You need to convert them to the desired data types within your program using parsing methods.
What are some common use cases for command-line arguments in Java applications?
Command-line arguments are commonly used for configuring program behavior, specifying input/output file paths, setting program options, and more, providing flexibility to the application.