×
☰ See All Chapters

Java Command-Line Arguments

In case if you like main method to act in a particular way depending on the input provided at the time of execution, you can pass the inputs to main methods as command line arguments. Command line arguments are parameters that are supplied to the main method at the time of invoking it for execution.

Main method

Every Java application program must include the main() method. Java program execution starts from main method. This is the starting point for the interpreter to begin the execution of the program. A Java application can have any number of classes but only one of them must include a main method to initiate the execution.

public class HelloWorld {

        public static void main(String[] args) {

                System.out.println("Hello World");

        }

}

main() method declares a parameter String[] args which contains an array of objects of the class type String. You can pass zero or any number of inputs to String[] args.

When you run a Java program from the command prompt, you can input arguments that get passed to the main() method as strings. For example, suppose that you entered the following command to run a program:

java <name of program> Hello  2 "Manu"

This command has three command-line arguments beyond the java <name of program> command: Hello, 2, and Manu.  (Arguments are separated by spaces unless placed in double quotes.) These three arguments are passed into main() and placed in the args parameter. The args parameter is an array of strings that can hold as many command-line arguments as you enter.

To access these arguments within main(), you use args with a subscript in square brackets. For example, args[0] is the first argument, args[1] is the second, and so on. In the current example, args[0] will be the string “Hello,” args[1] will be “2” and args[2] will be “Manu”

Java Command-Line Arguments Example

public class HelloWorld {

        public static void main(String[] args) {

                int totalNumberOfArgs = args.length;

                System.out.println("Total number of inputs recieved: " + totalNumberOfArgs );

                int i = 0;

                while (i < totalNumberOfArgs) {

                        System.out.println(args[i]);

                        i++;

                }

        }

}

Above program illustrates the use of command line arguments. Compile and run the program with the command line as follows:

java HelloWorld Hello 2 "Manu"

The output of the program would be as follows:

java-command-line-arguments-0
 

All Chapters
Author