Command line arguments in Java are used to pass arguments to the main program. When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument. The arguments have to be passed as space-separated values, and we can pass strings and primitive data types as command-line arguments. The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. When an application is launched, the runtime system passes the command-line arguments to the applications main method via an array of Strings. The arguments will be converted to strings and passed into the main method string array argument. We can check these arguments using the args.length method.
Here is an example of a simple Java class to print command line argument values:
package com.journaldev.examples;
public class CommandLineArguments {
public static void main(String[] args) {
System.out.println("Number of Command Line Argument = "+args.length);
for(int i = 0; i< args.length; i++) {
System.out.println(String.format("Command Line Argument %d is %s", i, args[i]));
}
}
}
If we run this class without any arguments, the output will be:
$ java com/journaldev/examples/CommandLineArguments.java
Number of Command Line Argument = 0
If we pass some arguments to the main class, we have to pass the arguments as space-separated values:
$ java com/journaldev/examples/CommandLineArguments.java "A" "B" "C"
Number of Command Line Argument = 3
Command Line Argument 0 is A
Command Line Argument 1 is B
Command Line Argument 2 is C
We can also pass primitive data types as command-line arguments:
$ java com/journaldev/examples/CommandLineArguments.java 1 2 3
Number of Command Line Argument = 3
Command Line Argument 0 is 1
Command Line Argument 1 is 2
Command Line Argument 2 is 3