Command line interfaces are a great option if your program is primarily used by developers or if it needs to be accessed programmatically through bash scripts. In this tutorial - directed at Java developers - you will learn why command line arguments are useful, how to use command line arguments in Java, and discover some examples that you can use to build your own command line applications. A Java command line program accepts values from the command line during execution. With command line programs, you do not need a to interact with or pass inputs into your program. Command line programs are useful if you use to run commands on a remote system or if your program is intended to be run via automation scripts that don’t need a GUI. graphical user interface (GUI) SSH Java command line arguments are arguments that are passed to your program via a terminal or shell command. They make your Java program more configurable by giving users or scripts running your software a way to specify input parameters at run time. In this detailed tutorial, you’ll learn how to: Create a simple Java command line application Use single and multiple arguments in a Java CLI application Support flags and CLI responses in your command line arguments Use two popular third-party libraries to handle command line arguments Use an IDE to run a Java command line application A Java Command Line Application The is typically the entry point for a Java class. The JVM passes the command line argument through the parameter of the , so you can fetch these arguments by accessing this parameter. main() method String[] args main() method Let’s look at a simple Java command line application: To compile the program from command line, use where SimpleCommandLinePgm.java is the name of your Java file: javac { { System.out.println( ); System.out.println( ); javac SimpleCommandLinePgm.java class SimpleCommandLinePgm public static void main (String[] args) "This is a simple command line program!" "Your Command Line arguments are:" // loop through all arguments and print it to the user for (String str: args) { System.out.println(str); } } } This will compile your Java application and create a file, which can be executed with the java command. .class Executing a Java Command Line Script with One Argument arguments typically follow the name of the program when it is executed, so to execute your newly compiled class, run the following from your terminal: Command Line java SimpleCommandLinePgm one is the name of the compiled Java program without extension. SimpleCommandLinePgm .java your first command line argument to the program one You should see the following output: This is a simple command line program! Your Command Line arguments are: one Executing a Java Command Line Script with Multiple Arguments Now that you’ve executed a Java command line class with one argument, let’s look at how this changes with multiple command line arguments: java SimpleCommandLinePgm one two three four This command looks almost the same, but as you can see, there are now four arguments after the name of the program ( ). Each item in your list of command line arguments is separated by space. one two three four This time, you’ll see something like this: This is a simple command line program! Your Command Line arguments are: one two three four Now that you've seen how to use command line arguments in your Java applications, you have a good starting point, but these examples require you to pass arguments in order. What if you want your script to accept named values as input? In the next section, you'll see how to create and execute a Java program that accepts and parses command line arguments as key-value pairs. Executing a Java Command Line Script with Named Arguments Allowing users to enter named arguments into a Java command line application makes your program much more flexible. It allows users to leave out some arguments, and it makes your interface more intuitive as users running the application can tell what each argument might do based on the key name. By default, Java doesn't accept key-value pairs via the CLI. However, the arguments can be passed using the , which passes the key-value pair arguments as arguments to the JVM itself. -D parameter This class shows how the key value pair arguments can be accessed from your Java program using the method: system.getProperty() { { System.out.println( ); public class AdvancedCommandLinePgm public static void main () "This is an advanced command line program!" // Get the value using the System.get Property and print it. System.out.println("Username is: " + System.getProperty("userName")); } } After you compile the program, you should be able to run it with a command like this: java -Dusername=Vikram AdvancedCommandLinePgm # Output This is an advanced command line program! Username is: Vikram While this method of named arguments in a Java command line program works, it’s not the most elegant solution. In the next section, you'll learn how to use two different third-party libraries to accomplish these same tasks without writing quite as much code yourself. Third-Party Libraries for Handling Java Command Line Arguments Using third-party libraries can save you a lot of time because the library handles validation and parsing. For example, you can make a parameter mandatory by simply setting a boolean value - you don’t need to write code to check if it’s been provided. The library will then throw an error with an appropriate message if the mandatory argument has not been supplied. Third-party libraries can also display help messages without the need for you to write more code. In this section, we’ll look at two third-party libraries that are commonly used for creating Java command line applications: and . PicoCli Apache Commons CLI Using PicoCli to Parse Java Command Line Arguments PicoCli is a single-file framework that allows you to create a Java program with almost zero code for handling command line arguments. It supports multiple command line syntax styles, including POSIX, GNU, MS-DOS, and it can generate highly customizable help messages with ANSI styles and colors to highlight important elements. To use the PicoCli, you need the in your buildpath, classpath, or (depending on your project configuration). jar Maven repository PicoCli can be implemented , which makes it easy for you to create a runnable Java program. Here’s an example of a simple PicoCli class: using the Callable or Runnable interfaces (name = , mixinStandardHelpOptions = , version = , description = ) { } @Command "userprofileinfo" true "User Profile Information V1.0" "Displays the User profile information." class PicoCliSamplePgm implements Runnable The annotation for the class denotes that this is a command line program. Here, I’m using several attributes for the annotation: @Command @Command - Name of the command line program name - Flag to denote whether Usage help and Version help should be added to your program as mixinStandardHelpOptions Mixin - Version information of the command line program, to display while printing the usage help version - Description of the command line program, to display while printing the usage help description PicoCli supports both named and positional arguments. For example, the following annotation shows how named arguments (called by PicoCli) are defined: options (names = { , }, required = , description = ) String firstName = ; @Option "-f" "--firstname" true "First Name of the user" private "First Name" Positional arguments (called ) don't have names and are by default. This example shows how you can define a positional parameter in PicoCli: parameters mandatory (index = ) String country; @Parameters "0" private You can read more about . PicoCli’s options and parameters in their documentation To use the command line arguments defined by PicoCli, you simply access them as variables inside your Java class’s run() method. Here’s a complete example of a Java class that uses PicoCli to parse and display user profile information passed via the command line: (name = , mixinStandardHelpOptions = , version = , description = ) { (names = { , }, required = , description = ) String firstName = ; (names = { , }, required = , description = ) String lastName = ; (names = { , }, required = , description = ) String email = ; @Command "userprofileinfo" true "User Profile Information V1.0" "Displays the User profile information." class PicoCliSamplePgm implements Runnable @Option "-f" "--firstname" true "First Name of the user" private "First Name" @Option "-l" "--lastname" true "Last name of the user" private "Last Name" @Option "-e" "--email" true "email id of the user" private "email" // Positional Parameters @Parameters(index = "0") private String country; @Option(names = { "-m", "--mobilenumber" }, required = false, description = "Mobile Number of the user") private String mobileNumber; @Override public void run() { // your business logic goes here... System.out.println("User First Name is: " + firstName); System.out.println("User Last Name is: " + lastName); System.out.println("User Email is: " + email); if (mobileNumber != null) { System.out.println("User Mobile Number is: " + mobileNumber); } if (country != null && !country.isEmpty()) { System.out.println("(Positional parameter) User's country is: " + country); } } // This example implements Runnable, so parsing, error handling, and help messages can be done with this line: public static void main(String... args) { int exitCode = new CommandLine(new PicoCliSamplePgm()).execute(args); System.exit(exitCode); } } When you , you’ll see output like the following: execute this program via your command line # Note: Depending how you include the PicoCli library, your command may vary. java -cp PicoCliSamplePgm -f Vikram -l Aruchamy -e name .com India -m # Output: User First Name is: Vikram User Last Name is: Aruchamy User Email is: name .com User Mobile Number is: (Positional parameter) User "myapp.jar;picocli-4.5.2.jar" @email 123456789 @email 123456789 's country is: India There are a lot of other things you can do with PicoCli, so be sure to refer to for more. their extensive documentation Using Apache Commons CLI to Parse Java Command Line Arguments Apache Commons CLI is another commonly used library in Java for command line parsing. It’s a good choice if you just need basic command line functionality and are already using other Apache libraries like . Commons IO To use the Apache Commons CLI, you need the in your buildpath, classpath, or the Maven repository. jar You can define command line options using the and objects available in Commons CLI. offers a list to hold all your program’s options, while lets you define the characteristics of each parameter individually. Options Option Options Option To parse command line parameters, Commons CLI uses the implementation of the interface. has a method called which accepts the object and the from the command line. Finally, you can use the to print the help information to the user. DefaultParser CommandlineParser DefaultParser parse() options args HelpFormatter The below example shows you a complete example of the Apache Commons CLI: { { Options options = Options(); Option name = Option( , , , ); name.setRequired( ); options.addOption(name); Option lastName = Option( , , , ); lastName.setRequired( ); options.addOption(lastName); Option email = Option( , , , ); email.setRequired( ); options.addOption(email); Option mobileNumber = Option( , , , ); mobileNumber.setRequired( ); options.addOption(mobileNumber); HelpFormatter formatter = HelpFormatter(); CommandLineParser parser = DefaultParser(); CommandLine cmd; { cmd = parser.parse(options, args); } (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp( , options); System.exit( ); ; } System.out.println( + cmd.getOptionValue( )); System.out.println( + cmd.getOptionValue( )); System.out.println( + cmd.getOptionValue( )); (cmd.hasOption( )) { System.out.println( + cmd.getOptionValue( )); } } } public class CommonsCliPgm Exception public static void main (String[] args) throws new new "f" "name" true "First Name" true new "l" "lastname" true "Last Name" true new "e" "email" true "Email" true new "m" "mobilenumber" true "Mobile Number" false new new try catch "User Profile Info" 1 return "User First Name is: " "name" "User Last Name is: " "lastname" "User Email is: " "email" if "m" "User Mobile Number is: " "mobilenumber" Now you can run the program optional parameter: with -m java CommonsCliPgm -f Vikram -l Aruchamy -e name .com -m # Output User First Name is: Vikram User Last Name is: Aruchamy User Email is: name .com User Mobile Number is: @email 123456789 @email 123456789 Or the optional parameter: without java CommonsCliPgm -f Vikram -l Aruchamy -e name .com # Output User First Name is: Vikram User Last Name is: Aruchamy User Email is: name .com @email @email As you can see, both the Apache Commons CLI and PicoCli make working with command line arguments in Java much easier and more robust. While you might not need them for very simple internal CLI scripts, it’s probably a good idea to consider using one of these options if you want help docs, error handling, and both optional and required argument support. Using an IDE with Java Command Line Arguments Using an IDE to develop your program can provide significant advantages. Typically, IDEs give you: Auto-complete and suggestions to speed up your developmentLine-by-line (rather than using control system integration that makes it easier to track changes to your code debugging System.println())Version In this section, you'll learn how to test and run command line scripts using the and . This section assumes you've already set up and have a working command line program (like one of the ones above). Eclipse IDE IntelliJ Idea Command Line Arguments in Eclipse IDE In Eclipse, right-click on the class you want to run. In the context menu, select . It will run the program: Run As -> Java Application If your command line program requires specific arguments, you'll see an error saying that command line parameters are missing. Behind the scenes, Eclipse will create a configuration. To add your arguments, right-click again and select . Run -> Run Configuration Eclipse will show you all the run configurations available in the workspace. Select the class name on the left side and enter your command line parameters, as shown in the below image. Click . You'll see output based on your command line parameters. Run User First Name is: Vikram User Last Name is: Aruchamy User Email is: name .com User Mobile Number is: (Positional parameter) User @email 123456798 's country is: India Command Line Arguments in IntelliJ In IntelliJ, the process is similar. Right-click on the class, and in the context menu, select : Run PicoCliSamplePgm.Main() It will run the program and if arguments are required, show an error. Now IntelliJ has created a configuration, so you can select . Select the class name on the left side as shown below and enter your command line parameters in the option. Click . Run -> Run Configurations Program Arguments Ok Run your program again using the option in the right-click context menu. You’ll see output based on your command line parameters. Run Conclusion In this tutorial, you’ve seen how to create a simple Java command line program that parses arguments and named options. You've learned how to create command line programs using PicoCli and the Apache Commons CLI package, and finally, how to use command line arguments with both the Eclipse and IntelliJ IDEs. Armed with this knowledge, you should be able to create robust command line applications in Java that use a variety of optional, required, and named arguments. Previously published at https://lightrun.com/java/java-tutorial-java-command-line-arguments/