top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Command line arguments in Java

Introduction

Java command line arguments serve as a powerful tool for enhancing the functionality and versatility of your Java applications. By allowing users to pass inputs through the command line, developers can create more interactive and adaptable programs. In this comprehensive guide, we will explore the practical usage of command line arguments in Java, covering everything from passing arguments to retrieving and parsing them. Whether you are a beginner or an experienced Java developer, this guide will equip you with the knowledge to effectively utilize command line arguments in your projects.

How to Pass Command Line Arguments in Java

To pass command line arguments in Java, you need to follow a specific syntax. The general one is as follows:

The program name should be the name of your compiled Java class file without the ".class" extension. The arguments can be any number of strings separated by spaces.

Examples of Passing Arguments

Let's explore a few examples of passing arguments in Java

Example 1: Command line arguments in Java to Add Two Numbers

Suppose we want to create a program that accepts two numbers as command line arguments and calculates their sum. Here's how you can pass the arguments:

In this example, the program expects two command line arguments to be provided as numbers. 

It checks if exactly two arguments are passed; otherwise, it displays an error message. Then, it parses the arguments into integers using Integer.parseInt() and calculates their sum. 

Finally, it displays the result on the console.

To run this program and pass the arguments, you can follow these steps:

i). Compile the Java file using the Java compiler:

ii). Run the compiled class file with the command line arguments:

ii). This will output:

You can replace 10 and 20 with any two numbers of your choice to perform the addition.

Example 2: Accepting Strings as Arguments

If you want to write a program that accepts two strings as command line arguments in Java, you can pass them like this:

In this example, the program expects two command line arguments to be provided as strings.

It checks if exactly two arguments are passed; otherwise, it displays an error message. 

Then, it retrieves the arguments from the args array and displays them on the console.

To run this program and pass the arguments, you can follow these steps:

i). Compile the Java file using the Java compiler:

ii). Run the compiled class file with the command line arguments

iii). The output will be:

Argument 1: Hello, World!
Argument 2: Java is awesome

You can replace "Hello, World!" and "Java is awesome" with any two strings of your choice to see them being displayed by the program.

Retrieving Command Line Arguments in Java

You can use the args parameter in the main method to retrieve command line arguments in a Java program. It is an array of strings that stores the command line arguments passed during program execution. Here's an example of how to retrieve command line arguments in a Java program using the args parameter in the main method:

In this example, the program checks if any command line arguments are provided. If there is none, it displays a message indicating that no arguments were given. 

Otherwise, it iterates through the args array using a loop and displays each argument along with its corresponding index.

To run this program and pass command line arguments, you can follow these steps:

i). Compile the Java file using the Java compiler:

ii). Run the compiled class file with the command line arguments:

Replace arg1, arg2, and arg3 with any values or strings of your choice. The program will display the provided command line arguments with their corresponding indices.

For example, if you run the program with the command line arguments Hello, Java, and World, it will output:

You can modify the program as needed to perform specific operations or validations on the retrieved command line arguments.

Parsing Command Line Arguments

Once you have retrieved the command line arguments, you may need to parse them into appropriate data types for further processing. Java provides various methods for parsing strings into integers, floats, or other data types based on your requirements.

In this example, the program checks if any command line arguments are provided. If there is none, it displays a message indicating that no arguments were given. 

Otherwise, it iterates through the args array using a loop and attempts to parse each argument into an integer using Integer.parseInt(). If the parsing is successful, it displays the parsed integer. 

If an argument cannot be parsed as an integer, it displays a message indicating that it is not valid.

To run this program and pass command line arguments, you can follow these steps:

i). Compile the Java file using the Java compiler:

ii). Run the compiled class file with the command line arguments:

The program will attempt to parse each argument into an integer. If an argument is a valid integer, it will display the parsed integer. If an argument cannot be parsed, it will display a message indicating that it is not a valid integer.

For example, if you run the program with the command line arguments 10, 20, abc, and 30, it will output:

Accessing Command Line Arguments

To access individual command line arguments, you can use array indexing with the args parameter. For example, args[0] will give you the first command line argument, args[1] will give you the second one, and so on. 

Here's an example that demonstrates accessing individual command line arguments in a Java program using array indexing:

In this example, the program checks if any command line arguments are provided. If there is none, it displays a message indicating that no arguments were given. 

Otherwise, it iterates through the args array using a loop and attempts to parse each argument into an integer using Integer.parseInt(). If the parsing is successful, it displays the parsed integer. 

If an argument cannot be parsed as an integer, it displays a message indicating that it is not valid.

To run this program and pass command line arguments, you can follow these steps:

i). Compile the Java file using the Java compiler:

ii). Run the compiled class file with the command line arguments:

The program will attempt to parse each argument into an integer. If an argument is a valid integer, it will display the parsed integer. If an argument cannot be parsed, it will display a message indicating that it is not a valid integer.

For example, if you run the program with the command line arguments 10, 20, abc, and 30, it will output:

Accessing Command Line Arguments

To access individual command line arguments, you can use array indexing with the args parameter. For example, args[0] will give you the first command line argument, args[1] will give you the second one, and so on. 

Here's an example that demonstrates accessing individual command line arguments in a Java program using array indexing:

In this example, the program checks if any command line arguments are provided. If there is none, it displays a message indicating that no arguments were given. Otherwise, it accesses individual arguments using array indexing and displays them on the console.

To run this program and pass command line arguments, you can follow these steps:

i). Compile the Java file using the Java compiler:

ii). Run the compiled class file with the command line arguments:

Replace arg1, arg2, and arg3 with the values or strings of your choice. The program will access and display the provided command line arguments individually.

For example, if you run the program with the command line arguments Hello, Java, and World, it will output:

You can access additional arguments by using additional indices, such as args[2], args[3], and so on.

Best Practices

When working with command line arguments in Java, it is essential to follow some best practices. These include validating user input, providing meaningful error messages for invalid arguments, and handling exceptions gracefully. Additionally, it's important to sanitize and secure any sensitive information passed as command line arguments.

Examples of Using Command Line Arguments in Java

1. Simple Calculator Application

Let's create a simple calculator application that accepts command line arguments for two numbers and performs basic arithmetic operations based on the user's choice.

In this example, the program expects three command line arguments: two numbers and an operator (+, -, *, or /). It checks if exactly three arguments are provided; otherwise, it displays an error message. Then, it retrieves the two numbers as double values and the operator as a char value. 

To run this calculator application and perform arithmetic operations, you can follow these steps:

i). Compile the Java file using the Java compiler:

ii). Run the compiled class file with the command line arguments:

Replace 10, 5, and + with the numbers and operators of your choice. The program will perform the arithmetic operation and display the result.

For example, if you run the program with the command line arguments 10, 5, and +, it will output:

Result: 15.0

Multiple command line arguments in Java

In Java, you can pass multiple command line arguments to your program when executing it. They are passed as strings and can be accessed through the args parameter in the main method.

Here's an example of how you can handle multiple command line arguments in Java:

To run it: 

Output:

Command line arguments in Java eclipse

To pass command line arguments in Java using Eclipse, you can follow these steps:

  • Open your Java project in Eclipse.

  • Right-click on the Java class file that contains the main method.

  • From the context menu, select "Run As" and then "Run Configurations".

  • In the "Run Configurations" window, select the Java application you want to run.

  • Go to the "Arguments" tab.

  • In the "Program arguments" section, enter the command line arguments separated by spaces.

  • Click "Apply" and then "Run" to execute the program with the specified command line arguments.

By providing the command line arguments in the "Program arguments" section, Eclipse will pass them to the program when it runs.

Java command line arguments file input

In this example, the program expects one command line argument, which is the name of the file to be read. 

It checks if a file name is provided; otherwise, it displays an error message. Then, it reads the content of the file using a BufferedReader and displays each line on the console. 

If an error occurs during file reading, it displays an error message.

To run this program and provide a file name as a command line argument, you can follow these steps:

i). Compile the Java file using the Java compiler:

ii). Run the compiled class file with the command line argument specifying the file name:

Replace input.txt with the actual file name you want to read. The program will read the content of the specified file and display it on the console.

For example, if you have a file named input.txt with the following content: 

Running the program with the command line argument input.txt will output:

Conclusion

Command line arguments in Java offer a flexible and efficient way to customize program behavior and provide inputs during program execution. By understanding how to pass, retrieve, and parse command line arguments, you can create more interactive and adaptable Java applications. Remember to follow best practices, handle invalid arguments gracefully, and prioritize security when dealing with sensitive information. Start incorporating command line arguments in your Java projects, and harness their full potential for enhancing user experience and program functionality.

FAQs

1. How can I pass command line arguments in Java?

Command line arguments can be passed when running a Java program from the command line. You can pass the arguments after the program name, separated by spaces.

2. How do I retrieve command line arguments in a Java program?

To retrieve command line arguments in a Java program, you can use the args parameter in the main method. You can access and process these arguments using array indexing.

3. How can I handle invalid command line arguments in Java?

To handle invalid command line arguments in Java, validate the input by checking the number of arguments and their values. Implement proper error handling to provide meaningful feedback to the user and ensure the program's stability. Remember to handle exceptions during argument validation.

Leave a Reply

Your email address will not be published. Required fields are marked *