Introduction:
Java allows you to pass command-line arguments to your Java programs when they are executed from the command line. These command-line arguments provide a way to customize the behavior of your program without modifying its source code.
Syntax:
The command-line arguments in Java are provided as an array of strings, which is available as the parameter of the main
method. The syntax for the main
method is as follows:
javapublic static void main(String[] args) {
// Your code here
}
Example:
Let's create a simple Java program that takes two numbers as command-line arguments and prints their sum.
javapublic class CommandLineArgumentsExample {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers as command-line arguments.");
return;
}
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("Sum: " + sum);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please provide valid integers.");
}
}
}
Explanation:
We first check if the
args
array has at least two elements. If not, we display a message asking the user to provide two numbers as command-line arguments.We use the
Integer.parseInt()
method to parse the string argumentsargs[0]
andargs[1]
into integersnum1
andnum2
, respectively.We then calculate the sum of
num1
andnum2
and store it in thesum
variable.Finally, we display the result by printing the sum to the console using
System.out.println()
.
Running the Program:
To execute the program and pass command-line arguments, follow these steps:
Open a command prompt or terminal.
Navigate to the directory where the compiled
.class
files are located.Type the following command and press Enter:
java CommandLineArgumentsExample 10 20
Output:
makefileSum: 30
In this example, we passed two numbers, 10 and 20, as command-line arguments, and the program calculated and displayed their sum.
Conclusion:
Command-line arguments in Java provide a flexible way to pass inputs to your program at runtime. They allow you to make your Java programs more versatile and interactive without modifying the code every time you want to change the inputs.
0 Comments