Command Line Arguments in Java

Java command-line argument is an argument that is passed at the time of running the Java program. Command-line arguments directly follows the program's name on the command line when it is executed. We can use these command-line arguments as input in our Java program.

Command line arguments provide a versatile way for Java programs to receive input from the user when executed. These arguments allow users to customize the behavior of a Java application without modifying the source code. In this tutorial, we will explore the fundamentals of command line arguments in Java, how to parse them, and best practices for handling user input from the command line.

  • We need to pass the arguments as space-separated values.

  • We can pass primitive data types(like int, char, double, float etc) as well as strings as command line arguments. However, JVM internally converts each command line argument into string and pass it to main() method of the program as an array of strings named args(String[] args).

  • JVM stores the first command-line argument at args[0], the second at args[1], third at args[2], and so on.

  • We can check the number of arguments passed to a program by checking the length of args using args.length.

Java program of command line argument

public class CommandLineArguments {
    public static void main(String[] args) {
        int index;
        // Iterate through all CLI arguments and print.
        for(index = 0; index < args.length; index++) {
            System.out.println("args[" + index + "]: "
               + args[index]);

Here are the steps to run above java program in the command line by passing command line arguments.

  1. Save above program as
  2. Open the command prompt window and compile the program by running following command
  3. Now suppose you want to pass three string arguments("Tech","Crash" and "Course") while running this program then you can pass the arguments after the class name. Execute your program by passing space separated command line arguments as follows:
    java CommandLineArguments Tech Crash Course
  4. You will see following output in your command prompt.
    args[0]: Tech
    args[1]: Crash
    args[2]: Course

Passing numeric command line arguments

We know that the data of command-line arguments passed to main() method are always in the form of String. We can use string parser methods to convert string to corresponding primitive data type like int, float, double etc.

public class NumberCommandLineArguments {
    public static void main(String[] args) {
        int index;
        // Iterate through all CLI arguments and print.
        for(index = 0; index < args.length; index++) {
            System.out.println("args[" + index + "]: "
                    + Integer.parseInt(args[index]));
java NumberCommandLineArguments 10 20 30
args[0]: 10
args[1]: 20
args[2]: 30

In above program, we used parseInt() method of Integer class to converts the string argument into an integer value. Similarly, we can use parseFloat() and parseDouble() method to convert a string argument into float and double respectively.

Important Points About Command-line Arguments
  • The command-line arguments passed to main method are in the form of String.
  • There is no limitation on the number of command-line arguments. We can use as many command line arguments as needed.
  • We can use the command-line arguments to specify the configuration information while launching our Java application.

Best Practices for Command Line Argument Handling

To ensure a smooth user experience and maintainable code, consider the following best practices when handling command line arguments in Java:
  • Provide a Help Option : Include a help option that displays information about how to use the program and the available command line options. This helps users understand how to interact with your application.

  • Validate Input : Implement robust input validation to handle invalid or unexpected input gracefully. This includes checking for the correct number of arguments, ensuring they are in the expected format, and providing informative error messages.

  • Use Meaningful Option Names : Choose clear and meaningful names for your options and arguments. This contributes to the readability and usability of your command line interface.

  • Document Your Command Line Interface : Document the expected command line interface in your project documentation. Clearly specify the purpose and usage of each option, flag, or argument to help users and developers understand how to interact with your program.

  • Consider Default Values : For optional arguments, consider providing default values. This can simplify the user's experience by reducing the need to specify certain options every time the program is executed.

  • Handle Edge Cases Gracefully : Anticipate edge cases and handle them gracefully. This includes scenarios where required arguments are missing, invalid values are provided, or unexpected combinations of options are used.

Conclusion: Harnessing the Power of Command Line Arguments

Command line arguments in Java empower developers to create flexible and customizable programs. Whether you're building a simple utility or a complex application, understanding how to parse and handle command line input is a crucial skill. By following best practices, validating input, and leveraging external libraries when necessary, you can create command line interfaces that are user-friendly, robust, and well-documented.

As you continue your Java journey, consider incorporating command line arguments into your toolset, and explore more advanced features provided by libraries like Apache Commons CLI. Mastering the art of command line argument handling will not only enhance your programming skills but also contribute to the overall usability and accessibility of your Java applications. Happy coding!