Big Data and Hadoop Training @$80 or Rs. 6,000 only - valid till Oct 17th Apply Now!

Command line argument in java

Ads
 

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

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

Ads

Ads