Pass Command Line Arguments
class CommandLineArguments
{
public static void main(String args[])
{
if(args.length == 0)
{
System.out.println("Running the program with no arguments");
}
else if(args.length == 1)
{
System.out.println("Running the program with one argument - " + args[0]);
}
else if(args.length == 2)
{
System.out.println("Running the program with two argument - " + args[0] + " and " + args[1]);
}
else
{
System.out.println("Invalid number of arguments only 0 or 1 or 2 arguments accepted.");
}
}
}
OUTPUTRunning the program with no arguments
DESCRIPTIONIf we execute this program as 'java CommandLineArguments wqr SASS
', then wqr
and SASS
will be considered as parameters. A String
array containing these arguments will be created and passed to the main
method. Since the name of the main method parameter is args
, we can access these parameters using args[0]
and args[1]
. We can use args.length
to get the number of parameters. In this case, it will be 2
.
If we run the program using 'java CommandLineArguments 234
', the number of arguments (args.length
) will be 1
and it can be accessed using args[0]
. Please note that although we are passing 234
, which is integer, it is treated as String
. If needed, we can convert this String
into Integer
using Integer.parseInt
method.
THINGS TO TRY
- Download this program locally and compile and run using the commands '
java CommandLineArguments
', 'java CommandLineArguments 234
', 'java CommandLineArguments wqr SASS
' and 'java CommandLineArguments param1 param2 param3
'. Observe that the output printed is different for different parameters.
Below image shows how the above program gives different output depending upon the arguments passed.
Below is an another example of command line arguments. Here we are taking only one argument and then printing that argument. If you run the following program using '
java EchoName Sachin
', then it will print
Hello Sachin. But if you run with out any arguments, then it throws an
ArrayIndexOutOfBoundsException
, since there is no element at the index 0.
class EchoName
{
public static void main(String s[])
{
System.out.println("Hello " + s[0]);
}
}