Menu
Topics Index
...
`

Pass Command Line Arguments - Java Example Program


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.");
    
        }
    
    }
}
OUTPUT

Running the program with no arguments

DESCRIPTION

If 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.

© meritcampus 2019

All Rights Reserved.

Open In App