Java Command Line Arguments
A user can pass any number of arguments to a Java applications at runtime from the OS command line. The main() method declares a parameter named args[] which is a String array that accepts arguments from the command line. These arguments are placed on the command line and follow the class name when it is executed. For example,
Java EmployeeDetail Roger Smith Manager
Here, EmployeeDetail is the name of a class and Roger, smith, and manager are command line arguments which are stored in the array in the order that they are specified. When the application is launched, the runtime system passes the command line argument to the application’s main() method using a String array, args[]. Note, that the array of strings can be given any other name. The args[] array accepts the arguments and stores them at appropriate locations in the array. Also, the length of the array is determined from the number of arguments passed at runtime. The arguments are separated by a space.
The basic purpose of command line arguments is to specify the configuration information for the application.
As already learnt, that the main() method is the entry point of a Java program, where objects are created and methods are invoked.
The staticmain() method accepts a String array as an argument as depicted in Code Snippet below:-
public static void main(String[] args){}
The parameter of the main() method is a String array that represents the command line argument. The size of the array is set to the number of arguments specified at runtime. All command line arguments are passed as string.
To run the program with command line arguments at command prompt, do the following:
- Open the command prompt.
- Compile the java program by writing the following statements
Javac CommandLine.java
3.Execute the program by writing the following statement:
Java CommandLine Roger Smith Manager (pass the argument)