Java Programs  «Prev  Next»
Lesson 5Customizing applications with command-line arguments
ObjectivePass information to Java applications with command-line arguments.

Pass information to Java applications with command-line arguments

Customizing Applications with command-line Arguments

In the previous lesson that the main() method has some additional information listed after the method name. This information is actually an application customization feature known as command-line arguments.
Command-line arguments provide custom information to an application. They are entered on the command-line when an application is executed using the Java interpreter. Following is an example of passing a command-line argument to an application named LifeCalc that calculates the number of days, hours, and minutes that you have lived:
java LifeCalc 28

As you can see, the single command-line argument is entered on the command-line just after the application name. Following are the results of this command:
You have lived 10220 days.
Or you can think of it as 245280 hours.
Better still, how about 14716800 minutes.

Handling command-line arguments

The key to command-line arguments can be found in the main() method[1]:
public static void main(String[] args)

The word args inside the parentheses is a method parameter, which is information passed into a method that the method might need to know about. In this case, the args parameter contains the list of command-line arguments entered by the user at the command-line.
The argument list is stored as an array of strings, which is basically a list of text. You learn about both arrays and strings in the next module, but for now just think of the args parameter as a container that holds the arguments passed into an application on the command-line. You can access each command-line argument individually.

You can determine the length of an array from its length data member. For example, the number of command-line arguments is determined by the following data member:
args.length
[1] main() method: The main method is a method within a Java application that is called by the Java interpreter to run the application.