Command-Line Arguments
Overview
Java parses command-line arguments specified after the name of the class:java Class arg1 arg2 arg3 ...The runtime system passes the command-line arguments to the app's main method via an array of Strings called args.
- To display command-line arguments:
public class Echo { public static void main (String[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); } } $ java Echo Drink Hot Java Drink Hot Java- To display the output on a single line, enclose the arguments in double quotes:
$ java Echo "Drink Hot Java" Drink Hot Java- To display the number of command-line arguments:
public class Echo { public static void main (String[] args) { numberOfArgs = args.length; System.out.println(numberOfArgs); } }- To parse numeric command-line arguments, convert String arguments to a number. For example, to convert an argument of "144" to an int:
int firstArg; if (args.length > 0) firstArg = Integer.parseInt(args[0]);parseInt throws a NumberFormatException if the format of args[0] isn't valid.
![]()