by Dinesh Thakur

Command Line Arguments are parameters that are supplied to the application program at the time of invoking it for execution. We can write Java programs that can receive and use the arguments provided in the command line.

e.g. publicstatic void main (String args[]). args is declared as an array of strings and arguments provided in the command line are passed to the array args as its elements.

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

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.java sorts lines in a file. To sort the data in a file named

friends.txt, a user would enter :

java Sort friends.txt

When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String: "friends.txt".

The Echo example displays each of its command-line arguments on a line by itself

:

public class Echo {

public static void main (String[] args) {

for (String s: args) {

System.out.println(s);

}

}

}

 

The following example shows how a user might run Echo. User input is in italics.

 

java Echo Drink Hot Java

 

Drink

Hot

Java

 

Note that the application displays each word — Drink, Hot, and Java — on a line by itself. This is because the space character separates command-line arguments.

To have Drink, Hot, and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.

 

java Echo "Drink Hot Java"

 

Drink Hot Java