Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Beginners Command line argument in java

 
 

Share on Google+Share on Google+

Command line argument in java

Advertisement
In this section we are going to discuss about command line argument in java. Command line argument allow a user to pass arguments at the time of running the application , after the class name. Java allow user to pass any number of argument to the command line

Command line argument in java.

In this section we are going to discuss about command line argument in java. Command line argument allow a user to pass arguments at the time of running the application , after the class name. Java allow user to pass any number of  argument to the command line. When running the application, argument is given after a class name separated by space. Suppose we are running java application, then class name followed by argument to the command line. It accept into the string argument of main method.

Command line argument accept all argument as string, If we want the application to support numeric command line argument then the following code should be written.

int Arg;
	if (args.length > 0) {
	    try {
	        Arg = Integer.parseInt(args[0]);  // Converting to Integer.
	    System.out.println("Argument is ="+Arg);
	    
	    } catch (NumberFormatException e) {
	       System.out.println("Argument" + " must be an integer");
	        
	    }

Syntax:  java Classname argument1 argument 2 argument3 ....

Example: java Commandline Welcome to Rose India

public class Commandline {

public static void main(String args[])
{
int size=args.length;
if(size<1)
{
System.out.println("Please pass some value");
}

int counter=1;
for(int i=0;i<size;i++)
{
System.out.println( +counter+ " argument = "+args[i]);
counter++;
}
}
}

Output: After compiling and executing of above program.

In the above program we pass argument to command line as Welcome to Rose India , command line display it each line by itself , This is because space separate the command line argument. To do it as a single argument user would join them by enclosing quotation marks. like "Welcome to rose India" .

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 7, 2013

Related Tutorials

Discuss: Command line argument in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com