Saturday 23 May 2015

Using Command Line Arguments In Java

In this post we will learn how to pass command line arguments.

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.

>javac UsingArgument.java
>java UsingArgument Mahendhar

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 UsingArgument application in an array that contains a single String: "Mahendhar".

// Program using a commmand line arugment
/*
 *  Compilation:  javac UsingArgument.java
 *  Execution:    java UsingArgument yourname
 *
 *  Prints "Hellp, Mahendhar. How are you?" where "Mahendhar" is replaced by the
 *  command-line argument.
 *
 *  > java UsingArgument Mahendhar
 *   Output:
 *   Hello, Mahendhar. How are you?
 *  
 **/

public class UsingArgument {

    public static void main(String[] args) {
        System.out.print("Hello, ");
        System.out.print(args[0]);
        System.out.println(". How are you?");
    }

}


No comments:

Post a Comment