Java Command-Line Arguments


Command-line arguments in Java allow you to pass data to a Java program at the time of execution from the command prompt. They are commonly used when you need to provide input to a program without having to modify the source code. Command-line arguments are often employed in console-based applications for tasks like passing configuration settings, input files, or user options.


What Are Command-Line Arguments in Java?

Command-line arguments in Java are arguments that are passed to a Java program when it is executed from the command line or terminal. These arguments are stored in an array of String objects, which are passed to the main() method of the Java program.

The main() method in Java always has the following signature:

public static void main(String[] args)

Here, args is a String array that holds the command-line arguments.

How to Pass Command-Line Arguments

To pass command-line arguments, you provide them after the class name when running the Java program from the command prompt.

For example, if you run the program like this:

java MyProgram arg1 arg2 arg3

The values arg1, arg2, and arg3 are passed to the main() method in the args array.


Accessing Command-Line Arguments in Java

Inside the main() method, the args array contains the command-line arguments. The index of the array corresponds to the position of the argument. For example:

  • args[0] will contain the first argument (arg1)
  • args[1] will contain the second argument (arg2)
  • And so on...

If no arguments are passed, the args array will be empty (its length will be zero).

Example: Printing Command-Line Arguments

Here’s a simple Java program that prints all the command-line arguments passed to it:

public class CommandLineArgsExample {
    public static void main(String[] args) {
        // Check if arguments were passed
        if (args.length > 0) {
            System.out.println("Command-Line Arguments Passed:");

            // Iterate over the arguments array and print each argument
            for (String arg : args) {
                System.out.println(arg);
            }
        } else {
            System.out.println("No command-line arguments were passed.");
        }
    }
}

Explanation:

  • The program checks if any arguments were passed (args.length > 0).
  • If arguments are present, it iterates through the args array and prints each one.
  • If no arguments are passed, it prints a message indicating that no arguments were provided.

Running the Program:

To run this program from the command line, you would use the following syntax:

java CommandLineArgsExample Hello World 123

Output:

Command-Line Arguments Passed:
Hello
World
123

Working with Command-Line Arguments

Converting Arguments to Other Data Types

Since command-line arguments are always passed as String values, you may need to convert them into other data types (such as int, double, etc.) depending on the requirements of your program.

Example: Converting Command-Line Arguments to Integer

public class CommandLineArgsConversionExample {
    public static void main(String[] args) {
        if (args.length == 2) {
            try {
                // Convert arguments to integers
                int num1 = Integer.parseInt(args[0]);
                int num2 = Integer.parseInt(args[1]);

                // Perform a simple addition
                int sum = num1 + num2;
                System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
            } catch (NumberFormatException e) {
                System.out.println("Please provide valid integers.");
            }
        } else {
            System.out.println("Please provide exactly two integers.");
        }
    }
}

Explanation:

  • The program expects two integer arguments.
  • The arguments are parsed into int values using Integer.parseInt().
  • If the user provides invalid inputs (non-integer strings), the program catches the NumberFormatException and prints an error message.

Running the Program:

To run the program:

java CommandLineArgsConversionExample 5 10

Output:

Sum of 5 and 10 is: 15

If the user provides invalid arguments (e.g., java CommandLineArgsConversionExample 5 abc), the program will catch the exception and print:

Please provide valid integers.

Practical Use Cases for Command-Line Arguments

Command-line arguments are particularly useful in scenarios such as:

  1. Configuration Files: When you want to provide the path to a configuration file to the program at runtime.
  2. File Processing: When your program needs to process input files, you can pass the file path as an argument.
  3. User Options: When you need to pass various user options (like verbosity level, debugging flags, etc.).
  4. Data Processing: For operations that require passing parameters like numbers or strings to be processed.

Example: File Processing Using Command-Line Arguments

import java.io.File;

public class FileProcessor {
    public static void main(String[] args) {
        if (args.length == 1) {
            File file = new File(args[0]);

            if (file.exists() && file.isFile()) {
                System.out.println("File found: " + file.getName());
                // Add file processing logic here (e.g., read file contents)
            } else {
                System.out.println("File not found or invalid file path.");
            }
        } else {
            System.out.println("Please provide the path to the file.");
        }
    }
}

Explanation:

  • The program accepts a single command-line argument, which is expected to be a file path.
  • It checks if the file exists and is valid, and then processes it (you could add logic to read or modify the file here).

Running the Program:

To run the program with a file path argument:

java FileProcessor /path/to/file.txt

Output (if the file exists):

File found: file.txt

Output (if the file does not exist):

File not found or invalid file path.

Handling Multiple Command-Line Arguments

You can also handle multiple command-line arguments by accessing them through the args array. For example, you might want to pass multiple parameters like file paths, user credentials, or other values.

Example: Handling Multiple Arguments

public class MultiArgExample {
    public static void main(String[] args) {
        if (args.length == 3) {
            String username = args[0];
            String password = args[1];
            String filePath = args[2];

            System.out.println("Username: " + username);
            System.out.println("Password: " + password);
            System.out.println("File Path: " + filePath);
        } else {
            System.out.println("Please provide username, password, and file path.");
        }
    }
}

Running the Program:

java MultiArgExample user123 mypassword /path/to/file.txt

Output:

Username: user123
Password: mypassword
File Path: /path/to/file.txt