paint-brush
Command-Line Arguments In Java For Beginnersby@yayabobi
2,091 reads
2,091 reads

Command-Line Arguments In Java For Beginners

by mvpGrowApril 3rd, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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. Command line programs are useful if you use SSH to run commands on a remote system or if your program is intended to be run via automation scripts that don’t need a graphical user interface. In this detailed tutorial, you’ll learn how to create and execute a simple command line application.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Command-Line Arguments In Java For Beginners
mvpGrow HackerNoon profile picture

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 graphical user interface (GUI) to interact with or pass inputs into your program. Command line programs are useful if you use SSH 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.

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 main() method is typically the entry point for a Java class. The JVM passes the command line argument through the

String[] args
parameter of the
main() method
, so you can fetch these arguments by accessing this parameter.

Let’s look at a simple Java command line application:

To compile the program from command line, use javac where SimpleCommandLinePgm.java is the name of your Java file:

class SimpleCommandLinePgm {     public static void main(String[] args) {         System.out.println("This is a simple command line program!");         System.out.println("Your Command Line arguments are:"); // loop through all arguments and print it to the user          for (String str: args) {             System.out.println(str);         }     } }
javac SimpleCommandLinePgm.java

This will compile your Java application and create a

.class
file, which can be executed with the java command.

Executing a Java Command Line Script with One Argument

Command Line 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:

java SimpleCommandLinePgm one
  • SimpleCommandLinePgm
    is the name of the compiled Java program without
    .java
    extension.
  • one
    your first command line argument to the program

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 (

one two three four
). Each item in your list of command line arguments is separated by space.

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 -D parameter, which passes the key-value pair arguments as arguments to the JVM itself.

This class shows how the key value pair arguments can be accessed from your Java program using the

system.getProperty()
method:

public class AdvancedCommandLinePgm { public static void main() { System.out.println("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: PicoCli and 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 jar in your buildpath, classpath, or Maven repository (depending on your project configuration).

PicoCli can be implemented using the Callable or Runnable interfaces, which makes it easy for you to create a runnable Java program. Here’s an example of a simple PicoCli class:

@Command(name = "userprofileinfo", mixinStandardHelpOptions = true, version = "User Profile Information V1.0", description = "Displays the User profile information.") class PicoCliSamplePgm implements Runnable { }

The annotation

@Command
for the class denotes that this is a command line program. Here, I’m using several attributes for the
@Command
annotation:

  • name - Name of the command line program
  • mixinStandardHelpOptions - Flag to denote whether Usage help and Version help should be added to your program as Mixin
  • version - Version information of the command line program, to display while printing the usage help
  • description - Description of the command line program, to display while printing the usage help

PicoCli supports both named and positional arguments. For example, the following annotation shows how named arguments (called options by PicoCli) are defined:

@Option(names = { "-f", "--firstname" }, required = true, description = "First Name of the user") private String firstName = "First Name";

Positional arguments (called parameters) don't have names and are mandatory by default. This example shows how you can define a positional parameter in PicoCli:

@Parameters(index = "0") private String country;

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:

@Command(name = "userprofileinfo", mixinStandardHelpOptions = true, version = "User Profile Information V1.0", description = "Displays the User profile information.") class PicoCliSamplePgm implements Runnable { @Option(names = { "-f", "--firstname" }, required = true, description = "First Name of the user") private String firstName = "First Name"; @Option(names = { "-l", "--lastname" }, required = true, description = "Last name of the user") private String lastName = "Last Name"; @Option(names = { "-e", "--email" }, required = true, description = "email id of the user") private String email = "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 execute this program via your command line, you’ll see output like the following:

# Note: Depending how you include the PicoCli library, your command may vary. java -cp "myapp.jar;picocli-4.5.2.jar" PicoCliSamplePgm -f Vikram -l Aruchamy -e name@email.com India -m 123456789 # Output: User First Name is: Vikram User Last Name is: Aruchamy User Email is: name@email.com User Mobile Number is: 123456789 (Positional parameter) User's country is: India

There are a lot of other things you can do with PicoCli, so be sure to refer to their extensive documentation for more.

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 jar in your buildpath, classpath, or the Maven repository.

You can define command line options using the Options and Option objects available in Commons CLI.

Options
offers a list to hold all your program’s options, while
Option
lets you define the characteristics of each parameter individually.

To parse command line parameters, Commons CLI uses the DefaultParser implementation of the

CommandlineParser
interface.
DefaultParser
has a method called
parse()
which accepts the
options
object and the
args
from the command line. Finally, you can use the
HelpFormatter
to print the help information to the user.

The below example shows you a complete example of the Apache Commons CLI:

public class CommonsCliPgm {

    public static void main(String[] args) throws Exception {

        Options options = new Options();

        Option name = new Option("f", "name", true, "First Name");
        name.setRequired(true);
        options.addOption(name);

        Option lastName = new Option("l", "lastname", true, "Last Name");
        lastName.setRequired(true);
        options.addOption(lastName);

        Option email = new Option("e", "email", true, "Email");
        email.setRequired(true);
        options.addOption(email);

        Option mobileNumber = new Option("m", "mobilenumber", true, "Mobile Number");
        mobileNumber.setRequired(false);
        options.addOption(mobileNumber);

        HelpFormatter formatter = new HelpFormatter();

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd;

        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
            formatter.printHelp("User Profile Info", options);

            System.exit(1);
            return;
        }

        System.out.println("User First Name is: " + cmd.getOptionValue("name"));
        System.out.println("User Last Name is: " + cmd.getOptionValue("lastname"));
        System.out.println("User Email is: " + cmd.getOptionValue("email"));
        if (cmd.hasOption("m")) {
            System.out.println("User Mobile Number is: " + cmd.getOptionValue("mobilenumber"));

        }
    }
}

Now you can run the program with optional

-m
parameter:

java CommonsCliPgm -f Vikram -l Aruchamy -e name@email.com -m 123456789 # Output User First Name is: Vikram User Last Name is: Aruchamy User Email is: name@email.com User Mobile Number is: 123456789

Or without the optional parameter:

java CommonsCliPgm -f Vikram -l Aruchamy -e name@email.com

# Output
User First Name is: Vikram
User Last Name is: Aruchamy
User Email is: name@email.com

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 debugging (rather than using

System.println())Version
control system integration that makes it easier to track changes to your code

In this section, you'll learn how to test and run command line scripts using the Eclipse IDE and IntelliJ Idea. This section assumes you've already set up and have a working command line program (like one of the ones above).

Command Line Arguments in Eclipse IDE

In Eclipse, right-click on the class you want to run. In the context menu, select Run As -> Java Application. It will run the program:

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 Run. You'll see output based on your command line parameters.

User First Name is: Vikram User Last Name is: Aruchamy User Email is: name@email.com User Mobile Number is: 123456798 (Positional parameter) User'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 Run -> Run Configurations. Select the class name on the left side as shown below and enter your command line parameters in the Program Arguments option. Click Ok.

Run your program again using the

Run
option in the right-click context menu. You’ll see output based on your command line parameters.

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/