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:
Reading Integer Input: You can use the
Integer.parseInt()
method to convert a string to an integer.Run the program with an integer argument:
java IntegerInputExample 42
.Reading Double Input: To read a double value, use
Double.parseDouble()
.Run the program with a double argument:
java DoubleInputExample 3.14
.Reading Boolean Input: You can parse a boolean value from a string by using
Boolean.parseBoolean()
.Run the program with a boolean argument:
java BooleanInputExample true
.Reading String Input: For string inputs, you can directly access the command-line arguments as strings.
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