Thursday, July 29, 2010

Command-Line Parameters in java

Every Java program has a main method with a String[] args parameter. This parameter indicates that the main method receives an array of strings, namely, the arguments specified on the command line.
For example, consider this program:

public class Message
{
public static void main(String[] args)
{
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + a[i]);
System.out.println("!");
}
}


If the program is called as


java Message -g cruel world

then the args array has the following contents:

args[0]: "-g"

args[1]: "cruel"

args[2]: "world"

The program prints the message

Goodbye, cruel world!

Differing from cpp
In the main method of a Java program, the name of the program is not stored in the args array. For example, when you start up a program as



java Message -h world
from the command line, then args[0] will be "-h" and not "Message" or "java".
While in c++ program name is also stored


No comments:

Post a Comment

Chitika