Thursday, December 25, 2008

How do i pass command line arguments in Java

Here is the example of how to pass command line arguments to a java file.
In the below example, one argument will be passed with the java command, and later within the the progrm it is retrieved as a String. 
Few other details, whenever we execute a java command, the main method is called, and in the below example you can see a main method defined and accepts array of String as parameters.
This means, whenever we pass any command line parameter, it is accpetd with this main method, and  "String s1 = args[0];", this line retrieves the value from the arguments passed to main method. We need to remember here one thing particularly, i.e. if we are passing one argument then we can retrieve only one otherwise if any mismatch occurs, then it will throw an exception as ArrayIndexOutOfBound exception.

CommandLineExample.java
-----------------------------

public class  CommandLineExample
{
  public static void main(String[] args) 
  {
    String s1 = args[0];
    System.out.println("Hello..  "+ s1);
  }
}
------------------------------
The above file is meant to recieve only one argument as command line argument.

How to execute and pass the command line argument, please follow the below instruction:
1. Open Command Prompt.
2. Go to the folder location where you have saved the above file as CommandLineExample.java.
3. Compile the Java file CommandLineExample.java
4. Once compilation is successfull, its turn for running the code..
5. Provide command as java CommandLineExample John and press enter
6. You can see a extra text is added other then java command and file name i.e. John, this is the string argument which i am passing to the CommandLineExample's main method.
Note: You can pass more then one number of arguments also. Whenever it is passed to the main method, all the arguments type are considered as String type. If you want to pass some numeric value then , you need to type cast it within the java code, and can use based on your requirement which is again a quite easy process.
6. You will se a message as Hello..  John

For extra help, i am providing the commandline texts here:
---------------------------------------------
--comment : below line will compile the file
C:\Temp>javac CommandLineExample.java
--comment : below line will execute the file, taking the last text i.e. John as command line argument
C:\Temp>java CommandLineExample John
Hello..  John
----------------------------------------------

Please provide you comments if any...

No comments:

Post a Comment