Positional Parameters in Java: An Update

DZone 's Guide to

Positional Parameters in Java: An Update

In this follow-up to a previous post about positional parameter parsing takes some crowdsourced lessons and turns them into a better solution.

· Java Zone ·
Free Resource

Recently, I published an article titled Overcoming Positional Parameter Parsing in Java, where I presented a few methods that can be used to help programmers overcome the attitude of referring to command line arguments as args[0], args[1], and so on.

The article was viewed by many people, but most importantly, there was a lot of 'constructive' feedback. This, in other words, is to say that many pulled my ears and pointed out the flaws in the code.

I would like to say that all the comments presented a valid point — the most important point being that many times we get caught up in things that we learned years ago. We continue to hold onto old things without realizing that many changes have taken place.

In this follow-up, I would like to mention one more method of handling command line parameters. This method, as you will realize, is by far the simplest to implement and understand.

Method 4

. . .
public static void main(String[] args)
    String inFile = null;
    String outFile = null;
    Map<String, String> cmdOptions = new TreeMap<String, String>();
    for ( int i = 0; i < args.length; i++ ) {
        if ( !cmdOptions.containsKey(args[i]) ) {
            if ( (i+1) < args.length ) {
                cmdOptions.put(args[i], args[i+1);
    inFile = cmdOptions.get("-i");
    outFile = cmdOptions.get("-o");
    . . .
. . .


Thanks to my fellow programmers who pointed me towards a better implementation.

command line ,java ,parsing ,positional parameters ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}