Command Line Arguments in Java - Accessing and Mapping to Data Types

Introduction

Command line arguments (parameters) are strings of text used to pass additional information to a program when an application is run through the command line interface (CLI) of an operating system.

In this tutorial, we'll be accessing the arguments (parameters) passed into the main method of a Java application and reading them. We'll also map them to different data types so that we can handle them and alter the flow of the code based on the input.

Accessing Command Line Arguments

The entry-point for every Java program is the main() method:

public static void main(String[] args) {
    // Do something
}

The arguments passed to the program as it was initialized are stored in the args array. Alternatively, Java also supports a vararg in this place:

public static void main(String... args) {
    // Do something
}

That being said, we can easily access each argument passed into this method. Let's start out by printing them out, one by one:

public class Main {
public static void main(String[] args) {
    for (int i = 0; i < args.length; i++)
        System.out.println(String.format("Argument %d: %s", i, args[i]));
    }
}

We'll then compile this .java file:

javac Main.java

After which, we can run it:

java Main Hello World

This results in:

Argument 0: Hello
Argument 1: World

Mapping Arguments to Data Types

The arguments themselves are an array of Strings. So really, everything we pass is a String. Though, we can convert Strings into different data types as well:

java Main Hello 15 true 

This prints out:

Argument 0: Hello
Argument 1: 15
Argument 2: true

Say we wanted to allow the users to print a String a set number of times, and have a flag that toggles a log message that displays the number of the iteration. The arguments provided above would thus print Hello 15 times, with a log message on each print() statement.

Let's do that:

public class Main {
    public static void main(String[] args) {

        String s = "";
        int n = 0;
        boolean flag = false;

        try {
            s = args[0];
        } catch (Exception e) {
            System.out.println("The first argument must be present.");
            System.exit(1);
        }
        try {
            n = Integer.parseInt(args[1]);
        } catch (NumberFormatException e) {
            System.out.println("The second argument must be an integer.");
            System.exit(1);
        }

        try {
            flag = Boolean.parseBoolean(args[2]);
        } catch (Exception e) {
            System.out.println("The third argument must be parseable to boolean.");
            System.exit(1);
        }

        for (int i = 0; i < n; i++) {
            System.out.println(s);
            if (flag)
                System.out.println(String.format("Iteration %d", i));
        }
    }
}

Now, let's compile the code again:

javac Main.java
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

And then, let's run it with no arguments:

java Main

We're greeted with:

The first argument must be present.

If we provide the arguments:

java Main Hello 5 true

We'll be greeted with:

Hello
Iteration 0
Hello
Iteration 1
Hello
Iteration 2
Hello
Iteration 3
Hello
Iteration 4

Setting Arguments in IDEs

This assumes that you run the code through the command line, which isn't always the case. Most people use IDEs to work on their projects, which have a convenient "Run" button instead.

Thankfully, you can tell the IDE to pass these arguments into the run call. Here are examples of how you can do that with some popular IDEs:

Eclipse

Under "Run"->"Run Configurations":

IntelliJ

Under "Run"->"Edit Configurations":

Conclusion

In this article, we've taken a look at how we can access the command line arguments passed into a Java application when it's run.

Then, we've mapped the passed arguments into different data types and handled them accordingly. With this in mind, it's easy to create simple CLI tools and alter the flow of code based on the passed arguments.

Last Updated: August 14th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms