Showing posts with label EXAMPLE JAVA PROGRAM FOR COMMAND LINE ARGUMENTS. Show all posts
Showing posts with label EXAMPLE JAVA PROGRAM FOR COMMAND LINE ARGUMENTS. Show all posts

Wednesday, February 15, 2012

COMMAND LINE ARGUMENTS

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.
  • The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run.
  • When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings.
  • 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.

Example:
  • Consider our Java program as sample.java with command line arguments.For that we have give the arguments in command prompt when invoking the program.
  • use java sample arg1 arg2 arg3....to run sample java program.
Program: 

public class Sample {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}
 
Compilation:
 
use the following code to run this program
javac Sample.java
java Sample Hai Hello World
 
Output:
 
Hai
Hello
World
 
Note: 
  • If you want give single command line argument for the same Output(above output), 
  • Compile the program and run using the code
    java Sample "Hai Hello World"

Output:
Hai Hello World


Parsing Numeric Command-Line Arguments

  • If your program needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "8", to a numeric value. 
Example:
public class Sample {
    public static void main (String[] args) {
int firstArg;
if (args.length > 0) {
    try {
        firstArg = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Argument"
            + " must be an integer");
        System.exit(1);
    }
}
}
} 
  • parseInt throws a NumberFormatException if the format of args[0] isn't valid. All of the Number classes — Integer, Float, Double, and so on — have parseXXX methods that convert a String representing a number to an object of their type