Command Line Argument in Java

Command Line Argument in Java


In java programming language the command line argument is a type of argument that we pass at the time when our program is going to run. We can use the arguments as input that is received from the console in java programming language. We can use the command line argument in java programming language to test or to check the behavior of the program for different values. We can pass a number of values to the program of java from the command prompt.


Simple example of command-line argument in java

Consider the following example in which one argument is passed and then we printed this argument:

CODE:

class ExampleCommandLine {

public static void main (String args []) {

system. out. println (“Command Line Argument: + args[0]);

}

}

The above code should be compiled by the following command:

javac ExampleCommandLine. java

The above code should be run by the following command:

java ExampleCommandLine Stuart

OUTPUT:

Command Line Argument: Stuart


Example of command line argument that prints all values:

Consider the following example in which the arguments that are passed are printed from the command line. It should be noted that to print all the arguments we will be using loop to traverse through an array:

CODE:

class S {

public static void main (String args []) {

for (int j = 0; j < args. length; j++)

system. out. println (args [j]);

}

}

The above program should be compiled by using the following command:

javac S. java

The above program should be run by using the following command:

java S Stuart Little 1 2 ABC

OUTPUT:

Stuart

Little

1

2

ABC