Sunday, November 14, 2010

How to use Java command Line Arguments

Whenever we need to pass information into our program during execution ,we can use command line arguments.The Command line arguments are actually the arguments of main() method and are of String Format.Basically command line arguments are those directly follow program's name on the command prompt.As I told earlier that are none other than simple main() programs arguments.All the command line arguments are stored in the form of String.So it is advised to change to required type like integer,char etc before using them in the main program.

Consider below Program as an Example:-

public class CommandArguments{

public static void main(String a[]){

int sum=Integer.parseInt(a[0])+Integer.parseInt(a[1]);

System.out.println("The Sum is :- "+sum);
}
}

As you can see that before adding the command arguments we typecasted them to Integer.This is an operation that is must before any numeric or other data type operation on command arguments.If we would not have typecasted the arguments then the result would be a concatenation of given values,this is because by default the command line arguments are stored as Strings.So it is must to typecast them before their use in application.Java Command Line arguments are mostly useful in command prompt based applications or text based applications.Where there is more of interaction between user and command prompt.

Reading Command Line Arguments:-
We can read command line arguments using the array provided as an argument in main() method.All command line arguments gets stored in that String array.We can use the array reference to point to their values.Lets consider below example:-


public class CmdArg{

public static void main(String arg[]){
if(arg.length<2){
for(int i=0;i<2;i++)
System.out.println("Argument is :- "+arg[i])
}
else
System.out.prinltn("Array out of Bound");
}

}


Related Links:-

The ? operator
Dynamic Initialization
Java Finalize Methods
How to Constructors of Super class

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey(Read More about him) .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP