Ticker

6/recent/ticker-posts

Java Command Line Arguments

Java Command Line Arguments

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:

java
public 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.

java
public 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:

  1. 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.

  2. We use the Integer.parseInt() method to parse the string arguments args[0] and args[1] into integers num1 and num2, respectively.

  3. We then calculate the sum of num1 and num2 and store it in the sum variable.

  4. 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:

  1. Open a command prompt or terminal.

  2. Navigate to the directory where the compiled .class files are located.

  3. 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.

Post a Comment

0 Comments