Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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");
    . . .
}
. . .


Acknowledgement

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

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,positional parameters ,parsing ,command line ,tutorial

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}