The user enters command-line arguments when invoking the application
and specifies them after the name of the class to be run. For example,
suppose a Java application called Sort sorts lines in a
file. To sort the data in a file named friends.txt, a
user would enter:
java Sort friends.txt
Strings. In the previous example, the command-line
arguments passed to the Sort application in an array that
contains a single String: "friends.txt".
Theexample displays each of its command-line arguments on a line by itself:EchoThe following example shows how a user might runpublic class Echo { public static void main (String[] args) { for (String s: args) { System.out.println(s); } } }Echo. User input is in italics.Note that the application displays each word —java Echo Drink Hot Java Drink Hot JavaDrink,Hot, andJava— on a line by itself. This is because the space character separates command-line arguments. To haveDrink,Hot, andJavainterpreted as a single argument, the user would join them by enclosing them within quotation marks.java Echo "Drink Hot Java" Drink Hot Java
If an application needs to support a numeric command-line argument, it must convert aStringargument that represents a number, such as "34", to a numeric value. Here is a code snippet that converts a command-line argument to anint:int firstArg; if (args.length > 0) { try { firstArg = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument must be an integer"); System.exit(1); } }parseIntthrows aNumberFormatExceptionif the format ofargs[0]isn't valid. All of theNumberclasses —Integer,Float,Double, and so on — haveparseXXXmethods that convert aStringrepresenting a number to an object of their type.