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 - argsarray 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 arguments- args[0]and- args[1]into integers- num1and- num2, respectively.
- We then calculate the sum of - num1and- num2and store it in the- sumvariable.
- 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 - .classfiles are located.
- Type the following command and press Enter: - java CommandLineArgumentsExample 10 20- Output: makefile- Sum: 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