Command Line Arguments

When using command-line arguments in Java, the inputs are generally treated as strings. To read user inputs of different data types from command-line arguments, you need to parse and convert these string inputs into the desired data types. Here are ways to read user inputs of various data types using command-line arguments:

  1. Reading Integer Input: You can use the Integer.parseInt() method to convert a string to an integer.

    public class IntegerInputExample {
        public static void main(String[] args) {
            if (args.length > 0) {
                int intValue = Integer.parseInt(args[0]);
                System.out.println("Integer value entered: " + intValue);
            } else {
                System.out.println("No integer value provided as an argument.");
            }
        }
    }

    Run the program with an integer argument: java IntegerInputExample 42.

  2. Reading Double Input: To read a double value, use Double.parseDouble().

    public class DoubleInputExample {
        public static void main(String[] args) {
            if (args.length > 0) {
                double doubleValue = Double.parseDouble(args[0]);
                System.out.println("Double value entered: " + doubleValue);
            } else {
                System.out.println("No double value provided as an argument.");
            }
        }
    }

    Run the program with a double argument: java DoubleInputExample 3.14.

  3. Reading Boolean Input: You can parse a boolean value from a string by using Boolean.parseBoolean().

    public class BooleanInputExample {
        public static void main(String[] args) {
            if (args.length > 0) {
                boolean boolValue = Boolean.parseBoolean(args[0]);
                System.out.println("Boolean value entered: " + boolValue);
            } else {
                System.out.println("No boolean value provided as an argument.");
            }
        }
    }

    Run the program with a boolean argument: java BooleanInputExample true.

  4. Reading String Input: For string inputs, you can directly access the command-line arguments as strings.

    public class StringInputExample {
        public static void main(String[] args) {
            if (args.length > 0) {
                String stringValue = args[0];
                System.out.println("String value entered: " + stringValue);
            } else {
                System.out.println("No string value provided as an argument.");
            }
        }
    }

    Run the program with a string argument: java StringInputExample "Hello, World!".

Remember to handle cases where the user may not provide the expected input or when the input does not match the expected data type. You should also consider checking the args.length to ensure that the expected number of arguments is provided before attempting to parse them.

Last updated