Using the Command Line Arguements

11:52 PM 2 Comments A+ a-

Command Line Arguements
Sometimes, there might arise a need for a program to run it in accordance with the specific input provided at the time of running the program. Command line arguements serve this purpose in java by allowing the user to input some values at the time of running the java program.
As the name implies, this feature is for only the programs which run on/from the command line interface. The input provided at the command line along with the instruction of running the java application, is stored in a String array and can be used in the program to make changes in the way program will behave.
They are directly passed to the main() of the java program.
public static void main(String args[])
the args[] is an array of strings, and it is called as command line arguements because the value of args[] can only be given at the run time from the command line. But wonder how to use it in your program?
This is simple, take a loot at the demo code that makes use of the command line arguements.

//Demo Code for using the Command Line Arguements in your program

class CommandLineArgs

public static void  main(String args[])
int sum = 0;
for(int i=0;i<args.length;i++)
sum = sum + Integer.parseInt(args[i]);
System.out.println("Sum is "+sum);

You might want to read or download the chapter wise Java SE tutorials.

Currently working at Symantec in Chennai. Previously worked as a Senior Software Engineer at IGATE. Loves to explore new things, loves to code and solve challenging problems with the help of it. Like any other normal person, loves to watch movies, listen to songs (specially when travelling, it is must), getting to know people, travelling and whatever makes me feel good!


Write comments
September 29, 2012 at 4:16 PM delete

You did not mention, why in the first place should we use command line arguments in any programming language?
If the same thing for user input can be done with the help of a BufferedReader or a Scanner objects...
Please try to be more specific bro, this simple information can be found on thousands of different places including wikipedia,
But your uniqueness makes it different from others... Hope i cleared something, and yes even i wanted to have an answer for that question I raised :)

Harish Sharma
September 29, 2012 at 5:05 PM delete

Thanks for the suggestion, now I am updating the post.
There may be some situations when we would want our program to run in some particular manner, particular no. of times etc. depending upon the input given to the program.
Command line arguements are just like giving the instruction of running the program with some specific input. Most of the programmers might not find them of any use, but still for many CUI applications, it might be useful.