View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

A Brief Introduction to Command Line Arguments in Java

Updated on 05/05/20254,280 Views

Command line arguments in Java are a powerful feature that allows users to pass information to a Java program during its execution, directly from the command line. This mechanism is frequently used in automation, scripting, and configuration-based applications where user input is provided externally rather than through interactive prompts or GUI-based forms.

When you execute a Java program using the java command in the terminal, you can provide a series of values—known as command line arguments—which are captured in the main() method of your program. These arguments are stored in the String[] args array, allowing the program to use them at runtime.

This concept not only enhances flexibility but also helps in customizing application behavior without changing the source code.

Learning Java? Take the next step with a full-fledged Software Engineering course designed for real-world success.

What Are Command Line Arguments?

In Java, command line arguments are the values passed to the main() method when a program is launched. The Java Virtual Machine (JVM) automatically captures these inputs and stores them in the String[] args array.

Syntax of the main() method:

public static void main(String[] args)

  • String[] args: This parameter stores command line arguments as an array of strings.
  • You can access them using array indexing like args[0], args[1], etc.

Boost your development career with these top-rated tech programs:

  upGrad Full Stack Development Bootcamp

• AI-Powered Full Stack Development by IIIT Bangalore

•  upGrad Cloud Computing & DevOps Certificate 

How to Pass Command Line Arguments

Let’s look at a simple example.

Example: HelloUser.java

public class HelloUser {
    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println("Hello, " + args[0] + "!");
        } else {
            System.out.println("Hello, user!");
        }
    }
}

Compile and Run:

javac HelloUser.java
java HelloUser Alice

Output:

Hello, Alice!
If no name is passed, it defaults to "user".

Must explore: Exploring Java Architecture: A Guide to Java's Core, JVM and JDK Architecture

Working with Multiple Arguments and Type Conversion

All command line arguments are stored as strings in Java. You must convert them manually to other types (e.g., int, double).

Example: Adding Two Numbers

public class AddNumbers {
    public static void main(String[] args) {
        if (args.length == 2) {
            try {
                int a = Integer.parseInt(args[0]);
                int b = Integer.parseInt(args[1]);
                System.out.println("Sum: " + (a + b));
            } catch (NumberFormatException e) {
                System.out.println("Please enter valid integers.");
            }
        } else {
            System.out.println("Provide exactly two integers.");
        }
    }
}

Run:

java AddNumbers 5 10

Output:

Sum: 15

Also read: Array in Java: Types, Operations, Pros & Cons

Best Practices When Using Command Line Arguments

1. Always Check Argument Count

Before accessing any command line argument, it’s crucial to verify that the expected number of arguments has been provided using args.length. Failing to do so can lead to an ArrayIndexOutOfBoundsException, causing your program to crash. 

For example, if your program expects two arguments but receives only one, attempting to access args[1] will result in an error. By checking the argument count beforehand, you ensure that your program behaves reliably and can respond with informative messages when arguments are missing.

Must explore: String Array In Java: Java String Array With Coding Examples

2. Use Meaningful Variable Names

Using meaningful variable names improves readability, maintainability, and clarity in your code. Instead of referencing arguments directly through indices like args[0] or args[1], assign them to clearly named variables such as String username = args[0]; or String filePath = args[1];. This makes the purpose of each argument immediately obvious to anyone reading the code, which is especially valuable in collaborative or large-scale projects.

3. Handle Exceptions Gracefully

Command line arguments are always passed as strings, and converting them into other data types (like integers or doubles) can lead to runtime exceptions if the input format is incorrect. For example, trying to convert "abc" to an integer will throw a NumberFormatException. 

To avoid such crashes and provide a better user experience, wrap your parsing logic in try-catch blocks and display helpful error messages guiding the user to provide valid input. This approach ensures your program can fail gracefully and continue running where possible.

Advanced Usage and Real-World Enhancements

As projects grow, parsing and validating command-line arguments manually becomes inefficient. Let's look at how to enhance your programs professionally.

Using Command-Line Parsing Libraries

1. Apache Commons CLI

A robust library that helps define options, parse arguments, and display help.

import org.apache.commons.cli.*;

public class CLIExample {
    public static void main(String[] args) throws ParseException {
        Options options = new Options();
        options.addOption("n", "name", true, "User's name");

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("n")) {
            System.out.println("Hello, " + cmd.getOptionValue("n") + "!");
        }
    }
}

2. Picocli

A modern and annotation-based library for rich CLI tools.

import picocli.CommandLine;
import picocli.CommandLine.Option;

public class PicoExample implements Runnable {
    @Option(names = {"-n", "--name"}, description = "Name of the user")
    String name;

    public void run() {
        System.out.println("Hello, " + name + "!");
    }
    public static void main(String[] args) {
        CommandLine.run(new PicoExample(), args);
    }
}

Also read: How to Code, Compile, and Run Java Projects: A Beginner’s Guide

Providing Help and Usage Instructions

Good CLI apps should support --help or -h to guide users.

if (args.length == 0 || args[0].equals("--help")) {
    System.out.println("Usage: java ProgramName <arg1> <arg2>");
    return;
}

CLI libraries like Apache CLI and Picocli auto-generate help sections for you.

Security Considerations

Passing sensitive data (like passwords or API keys) through command line arguments can expose them to system-level process monitors.

Best practice: Use environment variables or secure prompts instead.

import java.io.Console;

Console console = System.console();
String password = console.readPassword("Enter password: ");

Handling Special Characters and Input Redirection

Some characters (like <, >, &, |) are interpreted by the shell. To pass them literally, wrap them in quotes:

java MyApp "<filename>"
Also, be cautious with spaces in arguments—quote them too:
java MyApp "Hello World"

Passing Arguments in IDEs

Eclipse:

  • Right-click on the file > Run As > Run Configurations.
  • Go to the Arguments tab.
  • Enter arguments in the Program arguments field.

IntelliJ IDEA:

  • Run > Edit Configurations > Program arguments.

This helps users not comfortable with the terminal to test argument-based applications.

Comparison with Other Languages

Feature

Java

Python

C/C++

Entry Point

main(String[] args)

sys.argv[]

int main(int argc, char* argv[])

Argument Type

Always String

Always String

Raw C strings

Libraries for Parsing

Apache CLI, Picocli

argparse, click

getopt, boost::program_options

Java requires explicit type conversion, just like C/C++, whereas Python provides more dynamic handling.

Conclusion

Command line arguments in Java provide a flexible way to pass data into applications at runtime. While the basic mechanism using String[] args is powerful enough for simple tasks, advanced scenarios benefit greatly from parsing libraries, help options, input validation, and secure handling.

Whether you're building automation scripts, developer tools, or system utilities, mastering command line arguments gives your Java applications more power and versatility.

FAQs

1. What are command line arguments in Java?

Command line arguments in Java are values passed to a program when it is run from the terminal or command prompt. They are stored in the String[] args array of the main() method, allowing the program to receive dynamic input at runtime. This feature is commonly used for automation, configuration, and user-driven customizations without altering the source code.

2. How do I access command line arguments in Java?

To access command line arguments in Java, you refer to the String[] args array passed to the main() method. You can access individual arguments using array indices like args[0], args[1], etc., ensuring you check the length of the array to prevent ArrayIndexOutOfBoundsException.

3. Can Java command line arguments accept different data types?

Command line arguments are always passed as strings, so if you want to use them as other data types, such as integers or floats, you need to convert them manually. You can use methods like Integer.parseInt() for integers and Double.parseDouble() for floating-point numbers. Always handle exceptions like NumberFormatException to ensure the program doesn’t crash with invalid input.

4. What happens if no command line arguments are passed?

If no command line arguments are provided, the args[] array will be empty, and its length will be zero. In such cases, accessing elements in the array without checking args.length can result in an ArrayIndexOutOfBoundsException. Therefore, it’s important to include conditionals to handle scenarios where arguments may or may not be passed.

5. How many command line arguments can a Java program accept?

Java itself doesn’t impose a strict limit on the number of command line arguments you can pass; the operating system typically determines this based on the system's command line buffer size. While most systems support several thousand characters, it's best practice to keep the number of arguments manageable to ensure efficient handling and debugging.

6. Can I use spaces in command line arguments?

Yes, spaces are allowed in command line arguments, but they will split a single argument into multiple parts unless you enclose the argument in quotation marks. For example, if you want to pass a filename with spaces, you would use quotes: "My Document.txt".

7. How can I pass arguments in an IDE like Eclipse or IntelliJ?

In Eclipse, you can pass arguments by going to the Run Configurations > Arguments tab, where you can type in the desired arguments for your program. In IntelliJ, navigate to Run > Edit Configurations, then input arguments in the Program arguments field. These methods allow you to simulate passing arguments without needing to run the program from the command line.

8. What libraries can simplify argument parsing in Java? 

While manually handling command line arguments works fine for basic programs, using libraries like Apache Commons CLI or Picocli makes parsing more efficient and user-friendly. These libraries provide features like handling options and flags, generating help messages, and supporting complex argument structures.

9. How do I provide help instructions for users?

You can implement a --help flag to provide users with usage instructions on how to run the program, including available arguments and their expected formats. If you're using a library like Apache Commons CLI or Picocli, they automatically generate detailed help documentation. This is a good practice to improve user experience and make your CLI application more intuitive.

10. Are command line arguments secure for passing sensitive data? 

Command line arguments are not the most secure way to pass sensitive information, as they can be exposed in process lists or command history files on some operating systems. For secure data transmission, consider using environment variables or prompting users to input sensitive information interactively using Console.readPassword().

11. Can command line arguments support localization or international characters?

Yes, Java fully supports Unicode, meaning you can pass and process command line arguments in any language, including non-English characters like Chinese, Arabic, or Russian. However, ensure that the terminal or script you're using supports UTF-8 encoding to avoid misinterpretation of characters. 

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.