Back to Study Material Java

Command Line Arguments in Java

Command line arguments provide a way to pass information into a Java program at the moment it is launched, without modifying the source code or relying on ...

Command Line Arguments in Java

Passing Runtime Parameters via the Command Line

Command line arguments provide a way to pass information into a Java program at the moment it is launched, without modifying the source code or relying on interactive input during execution. They are especially useful for scripts, utilities, and server applications where runtime configuration, file paths, or mode switches must be specified externally.

Command line arguments reach the program through the String[] args parameter of the main method. When you run java Calculator add 5 10, the JVM populates args with three strings: args[0] is "add", args[1] is "5", and args[2] is "10". Every argument is a String regardless of its apparent type; numeric values must be converted explicitly with Integer.parseInt(), Double.parseDouble(), or similar methods.

Before accessing args elements, always verify that enough arguments were provided: if (args.length < 2) { System.out.println("Usage: java Calculator <operation> <number>"); System.exit(1); }. Accessing args[0] when args.length is 0 immediately throws ArrayIndexOutOfBoundsException. Providing a clear usage message before exiting makes the program much friendlier to users who invoke it incorrectly.

A complete working example: public class Adder { public static void main(String[] args) { if (args.length < 2) { System.out.println("Provide two numbers."); return; } int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println("Sum: " + (a + b)); } }. Running java Adder 15 27 prints Sum: 42. Running it with a non-numeric argument like java Adder hello 5 throws NumberFormatException, which in real code should be caught with a try-catch block.

Spaces in an argument value require quoting at the command line: java Greeter "John Doe" treats "John Doe" as a single argument, so args[0] is "John Doe". Without the quotes, Java and Doe would be two separate arguments.

For more complex argument parsing with named flags (like --output=file.txt or -v for verbose), consider using a library such as Apache Commons CLI or Picocli rather than parsing args manually. These libraries handle optional arguments, default values, type conversion, and usage help generation automatically.

Interview tip: A typical interview question presents a main method with String[] args and asks what happens if you run the program with no arguments and the code immediately accesses args[0]. The answer is an ArrayIndexOutOfBoundsException at runtime. Follow up by explaining how to guard against this with an args.length check, demonstrating defensive programming.