Thursday, December 25, 2008

How do I pass numeric value as command line argument to Java

Here is the example to pass numeric value as a command line argument is Java Class.

CommandLineNumExample.java
---------------------------------
public class  CommandLineNumExample
{
  public static void main(String[] args) 
  {
    int i = Integer.parseInt(args[0]);
    double d = Double.parseDouble(args[0]);
    // multiplying the value of i i.e command line argument with 2
    System.out.println("The Argument Number Value is  "+ (i*2)); 

    // multiplying the value of i i.e command line argument with 3
    // you can see a decimal value also as the argument is converted to double
    System.out.println("The Argument Double Value is  "+ (d*3));
  }
}
---------------------------------
Please read my previous example on How to pass Command Line Arguments in Java to get details about CommandLine arguments and how to pass arguments thru command line

The output will be 
---------------------
The Argument Number Value is  44
The Argument Double Value is  66.0
---------------------

For your help, i am providing the commands in sequence:
Note: 22 in the below command is the argument
----------------------------
C:\Temp>javac CommandLineNumExample.java

C:\Temp>java CommandLineNumExample 22
The Argument Number Value is  44
The Argument Double Value is  66.0
----------------------------

If you any comments or suggestion, please provide.

3 comments:

  1. sir my name is mohith i do have written a program using command line args but am geting the follwing error. My program is getting compiled but when i run the program am getting following output

    Program:
    class two
    {
    public static void main(String args[])
    {
    int a,b,c;
    System.out.println("enter any two values to add:");
    a= Integer.parseInt(args[0]);
    b= Integer.parseInt(args[1]);
    c=a+b;
    System.out.println("The sum of two values is:"+c);
    }
    }

    OUTPUT:
    enter any two values to add:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at two.main(two.java:7)

    ReplyDelete
  2. Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. teknisk analys aktier

    ReplyDelete