Java Command Line Arguments

By | October 23, 2018

If you have used other languages, you will probably be familiar with the idea of passing arguments to a program via the command line. This post shows you how you can do it with java.

In this post we’ll use a simple script to also take arguments from the command line. Read more about getting started with Java.

This is a file called JavaCommandLineInput.java

public class JavaCommandLineInput {
    public static void main (String[] args) {
        for (String arg : args) {

            System.out.println("Hello, " + arg + "!");

      }
    }
}

Much of this code is the same as in this simple Java example, but there are some other elements worth describing here.

‘String[] args’

The argument to the main method of the JavaCommandLineInput method is ‘String[] args‘. This provides a variable which contains any command line arguments provided when the compiled program is run. Java is designed for this ‘String[] args’ argument to be compulsory, so you will need to include it in your programs, even if you do not intend to provide arguments at the command line. The variable does not need to be called ‘args’ – it can be anything you want – although it is a strong convention for it to be ‘args’. It is also possible (and equivalent) to write ‘String args[]‘ rather than ‘String[] args’ and is a matter of choice and coding style as to which one you use.

Using the Command Line Arguments

Now that we know we can use the ‘args’ variable for command line arguments, it is a question of actually doing so. The ‘args’ variable is an array of strings (which makes sense as any values come directly typed from the command line). In the above example a ‘for-each’ loop loops through each of the values in ‘args’ and print it to the console with println().

Compile and Run the Code

Compile this code with

javac JavaCommandLineInput.java

You can then run this program with:

java JavaCommandLineInput Everybody

Which gives the output:

Hello, Everybody!