Command Line Arguments in Java

Every Java program has access to command line arguments. Command line arguments are a facility to pass in input Strings to your main method. Your application then needs to act upon the input passed. The command line arguments are different from other kinds of user inputs in that they are passed unconditionally and without any prompt.

How to Access Command Line Arguments

You may recall from one of our previous lessons that the signature of the main method is public static void main(String[] args) {

….

}

The args String array stores your command line arguments. Note that args is just a name, you can change it to whatever you like. The code below is as good as the previous one  –public static void main(String[] codingRaptor) {

….

}

Also, note that the type of input array is String[] .So, even if you pass a set of numbers, they will come in as String. It is the programmer’s duty to convert (and catch relevant Exceptions) the input Strings to appropriate data type.

Example of Command Line Arguments Usage

Demonstrated below is a simple program which expects integers as inputs and outputs the twice of the numbers passed to it.

Applying what we learned here, we run this code as follows java Multiply 1 2 3 4 5

The output (without the strings that we print) should be2 4 6 8 10

As you can see, all the inputs passed on the command line get stored on the input array args. We can access the values stored in this array and process them. We need to convert the values from String to approriate data type.

When to Use Command Line Arguments in Java?

Although command line arguments are a great way to pass in inputs, remember the following points –

  1. Use prompts to collect user input. Do not burden your users by mandating them to pass the input as arguments on command line. (The example shown above was solely for demonstration purposes. NEVER EVER force your users to provide input like this)
  2. For input parameters which are essential to initializing your program you should rely on command line arguments. For example, your application may display different GUI based on whether it is on a desktop or a smartphone. You can pass in the device type to main method.
  3. If input is lengthy, verbose or for some other reason cumbersome to input (for example input in binary form) you can give your users option to supply a file name as an argument. Again, do not collect application input from command line. You should collect application initialization inputs.
  4. Of course, and this goes without saying, never force your users to provide passwords on command line.

Leave a comment

Your email address will not be published. Required fields are marked *