Wednesday 13 November 2013

Command Line Aruguments in Java


This program echos the first command line argument.
What are command line arguments?

Command line argument is initial input to java application. These can be used as configuration information while launching any java application.

How to specify command line arguments?

Following is a syntax for "java" command

java [-options] class [args...]

So you can append number of command line arguments after class name by maintaining space between different arguments.
For eg.
java Echo one two three
Here, we are passing 3 arguments - one,two,three. My Echo program will print "one" in console for these arguments. It is easy to notice that args is a string array which stores all arguments passed by java command. We need to clear one thing about java array. In Java, array starts from 0th location. Hence args[0] is "one", args[1] is "two", args[2] is "three". (little bit funny for beginners!!!)

Well, This is nice. But remember we have to keep space between two arguments. What if I want to pass command line argument with a space like 'One space'?

It is possible to provide space in command line argument. For this you have to pass argument enclosed by double quotes("").
For Eg.
java Echo "One space" two three 
Now output of Echo program will be One Space. Yes, java considers any number of words separated by space inside "" as one single argument.

Putting it all together

command : java EchoPro "One space" two three

Output :
args.length : 3
args[0] : One space
args[1] : two
args[2] : three


No comments:

Post a Comment