Saturday 30 July 2011

Command Line Arguments in Java Program



Java application can accept any number of arguments directly from the command line. The user can enter command-line arguments when invoking the application. When running the java program from java command, the arguments are provided after the name of the class separated by space. For example, suppose a program named CmndLineArguments that accept command line arguments as a string array and echo them on standard output device.
java CmndLineArguments Mahendra zero one two three
CmndLineArguments.java
   /**
   * How to use command line arguments in java program.
   */
   class CmndLineArguments {

  public static void main(String[] args) {
    int length = args.length;
    if (length <= 0) {
    System.out.println("You need to enter some arguments.");
    }
   for (int i = 0; i < length; i++) {
    System.out.println(args[i]);
   }
   }
   }
Output of the program:
Run program with some command line arguments like: 
java CmndLineArguments Mahendra zero one two three
OUTPUT
Command line arguments were passed :
Mahendra
zero
one
two
three

No comments: