Command Line Arguments

Thinking

Command line arguments allow users to influence a Java program's behavior at runtime without changing its source code. They offer flexibility for different input values and configurations.

By learning how to use command line arguments, developers can create programs that accept input directly from the terminal, making them more dynamic and reusable.

Description

In Java, command line arguments are passed to the main() method as an array of strings: public static void main(String[] args).

  • Each space-separated token passed when running the program becomes a separate element in the args array.
  • Arguments must be parsed to their appropriate types (e.g., Integer.parseInt() for integers).
  • They allow for runtime flexibility without recompilation.

Video Resources

Java CLI Input

Working with inputs directly from the terminal.

Examples (code)

Using Command Line Arguments


public class CommandLineDemo {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("No arguments provided!");
        } else {
            System.out.println("You entered:");
            for (String arg : args) {
                System.out.println(arg);
            }
        }
    }
}
  

Parsing Integer Arguments


public class SumArgs {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Please provide two integers.");
            return;
        }
        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);
        System.out.println("Sum = " + (num1 + num2));
    }
}
  

Real-World Applications

CLI Tools

Used in command-line tools to accept arguments like file paths, flags, and options.

Automation Scripts

Automated Java tasks can use arguments to change behavior based on user input.

Testing and Debugging

Helps in running tests with various configurations or sample inputs directly from the terminal.

Interview Questions

Q1: What is the data type of command line arguments in Java?

Show Answer

All command line arguments are passed as String types in the String[] args array.

Q2: How can you access the first argument passed to a Java program?

Show Answer

You can access it using args[0] inside the main method.

Q3: What happens if you try to access an argument index that doesn't exist?

Show Answer

A ArrayIndexOutOfBoundsException will be thrown.