Command Line Arguments in JavaLast Updated : 7 Jan 2026 Java Command-line arguments allow you to pass input values to a program at runtime that makes the program easy to test and run with different data without modifying the code. What are Command-line Arguments in Java?Command-line arguments are inputs passed to a Java program at runtime through the console. They are received in the main() method as a String array (String[] args). Example: If you run: Then inside main(String[] args), This makes programs easy to test with different inputs. Why Use Command-Line Arguments?Command-line arguments offer a flexible way to pass input values to Java programs without changing the source code. It is particularly useful in scenarios like automation, where scripts need to run with different inputs, or configuration management, where settings change between environments (for example, dev, test, prod). They allow developers to test various input scenarios efficiently, making programs more dynamic and reusable. Rather than hardcoding values, users can supply them externally, which leads to cleaner code and easier maintenance. Example of Command Line ArgumentIn this example, we are receiving only one argument and printing it. To run this Java program, we must pass at least one argument from the command prompt. Output: Your first argument is: Andrew Execute the above program by using the following commands. How to Handle Missing Arguments?Accessing arguments that were not passed will cause an ArrayIndexOutOfBoundsException. To avoid this, always check the length of the args[] array: The above code snippet avoids crashes and improves the reliability of your code. Converting Argument TypesAll command-line arguments are passed as strings. If your logic needs integers, floats, or booleans, we must parse them: Always handle exceptions like NumberFormatException when converting input values. Example: Printing Multiple Values Using Command Line ArgumentsIn this example, we are printing all the arguments passed from the command line. For this purpose, we have traversed the array using a for loop. Output: Andrew 25 University of California Execute the above program by using the following commands. Important Points to Remember
ConclusionCommand line arguments in Java provide a flexible and efficient means of passing input to a programme at runtime. By supplying arguments through the main(String[] args) method, developers can customise programme behaviour without altering the source code. It makes Java applications more dynamic, testable, and suitable for automation. Next TopicObject vs Class |
We request you to subscribe our newsletter for upcoming updates.