Java Command-Line Arguments
Java allows us to pass arguments to the main()
method when running a program from the command line. These arguments are received as a String array (String[] args
).
Why Use Command-Line Arguments?#
- Dynamic input without modifying the code
- Used in real-world applications to provide configuration settings
- Helpful in automation and scripting
How Command-Line Arguments Work?#
When we run a Java program from the terminal, we can pass arguments after the class name:
- These arguments are stored in the
String[] args
array. args[0]
holds the first argument,args[1]
holds the second, and so on.
Example: Printing Command-Line Arguments#
How to Run in Terminal:#
Expected Output:#
Explanation:
- The
args
array stores the command-line arguments. args.length
gives the number of arguments passed.
Converting Command-Line Arguments to Other Data Types#
Since command-line arguments are always strings, we may need to convert them.
Example: Adding Two Numbers from Command-Line Arguments#
How to Run in Terminal:#
Expected Output:#
Explanation:
Integer.parseInt(args[0])
converts string arguments to integers.- The program calculates and prints their sum.
- If less than two arguments are provided, it prints an error message.
Handling Errors in Command-Line Arguments#
To avoid errors, always validate input before converting it.
Example: Handling Incorrect Input#
How to Run in Terminal:#
Expected Output:#
Key Takeaways#
✅ Command-line arguments are passed to main(String[] args)
.
✅ Arguments are stored as Strings and need to be converted if required.
✅ Always validate inputs to prevent errors.
✅ Useful for passing dynamic inputs without modifying code.
Conclusion#
- We learned how to use command-line arguments in Java.
- We saw how to convert arguments to integers and perform calculations.
- We also explored error handling when incorrect inputs are passed.
Command-line arguments make Java programs flexible and dynamic, widely used in real-world applications