Thursday 14 April 2016

Command Line Arguments In Java

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.

class Test { 
 public static void main(String[] args) {
      for (int i = 0; i < args.length; i++)
          System.out.println( args[i]);
 }
}


On a machine with the Oracle JDK installed, this class, stored in the file Test.java,
can be compiled and executed by giving the commands:


javac Test.java

java Test Drink Hot Java

producing the output:

Drink
Hot
Java


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

java Test "Drink Hot Java"

Drink Hot Java

Parsing Numeric Command-Line Arguments

 It must convert a String argument to respective types.Here is a code snippet that converts a command-line argument to respective types:


Class ParseCommandLine{
   public static void main(String args[]){
     String str = args[0]
     int i  = Integer.parseInt(args[1]);
     float f  = Integer.parseFloat(args[2]);
     double d  = Integer.parseDouble(args[3]);
     boolean b  = Integer.parseBoolean(args[4]);

     System.out.println(str);
     System.out.println(i);
     System.out.println(f);
     System.out.println(d);
     System.out.println(b);
   }
}

How To Compile & Run : 

javac ParseCommandLine 

java ParseCommandLine MyJava 15   2.4   5.67  true

Output :

MyJava 
15 
2.4 
5.67 true

No comments:

Post a Comment