Program for use of command line arguments

Program for use of command line arguments

Write a program to illustrate the use of command line arguments. Also implement
necessary exception handling.

Command-Line Arguments:

  • The args array stores command-line arguments passed when the program is run.
  • args.length gives the number of arguments passed.

Exception Handling:

  • NumberFormatException: Catches cases where the argument cannot be parsed to an integer.
  • ArrayIndexOutOfBoundsException: Catches cases where an expected argument doesn’t exist (e.g., trying to access args[0] when no argument is passed).
  • A generic Exception is used to catch any unexpected errors.

Example :

public class CommandLineExample {

public static void main(String[] args) {

    // Checking if command-line arguments are provided
    if (args.length == 0) {
        System.out.println("No command-line arguments provided.");
    } else {
        System.out.println("Command-line arguments:");

        // Loop through the arguments and print each one
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + (i + 1) + ": " + args[i]);
        }
    }

    // Demonstrating exception handling
    try {
        // Example: Try to convert the first argument to an integer
        if (args.length > 0) {
            int number = Integer.parseInt(args[0]);  // Parsing the first argument
            System.out.println("The integer value of the first argument is: " + number);
        }
    } catch (NumberFormatException e) {
        System.out.println("Error: The first argument is not a valid integer.");
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Error: No arguments provided for conversion.");
    } catch (Exception e) {
        System.out.println("Unexpected error: " + e.getMessage());
    }
}

}

To Run :

javac CommandLineExample.java

java CommandLineExample

java CommandLineExample 10

java CommandLineExample abc