Click here to close now.


Java IoT Authors: Flint Brenton, Liz McMillan, Pat Romanski, Jennifer Gill, Elizabeth White

Related Topics: Java IoT

Java IoT: Article

Parsing Command Line Arguments with Java

Parsing Command Line Arguments with Java

One of Java's great appeals is that the language provides out-of-the-box GUI development capabilities. Still, a lot of us use Java to write command line tools. Such tools are great to automate batch and offline processes. This article presents a framework that jump-starts the development of such tools.

Command line tools are usually invoked from a shell (e.g., DOS prompt, sh, ksh, etc.) and perform a certain task. The task can be customized based on the command line arguments. For instance:


attempts to open a telnet connection to host It uses the default telnet port. The next example:

telnet -p 3434

attempts a similar connection using port 3434.

Command line tools can be as simple or as complicated as the developer desires. An example of a simple command line tool is the echo command found in most shells. On the other hand, the Java compiler and the Java Virtual Machine (JVM) are complex command line tools.

Java presents the command line arguments in an array of strings. This is already a huge improvement over C and C++, in which the arguments are presented as an array of C strings, i.e., an array of pointers to arrays of characters. Yet it comes short of the developer's desire to get the arguments parsed and ready to use.

Since I published my 1997 C++ command line parsing framework (see Reference), many readers have e-mailed me with requests and suggestions. The top two requests have been for a Java implementation and an improvement to handle arrays of arguments. In this article I present a total rewrite of the framework with improvements for Java programmers.

Using the Framework
Before moving to the implementation I'll demonstrate how to use the framework to write a command line utility. Let's say you want to write a utility called "mycat" - like the UNIX cat - which takes a number of files and concatenates them together into a larger file. A -v option turns verbose output on and off. A -l option allows the insertion of extra empty lines between the files. The command would look like:

&127;mycat [-l ] [-v] file1 file2 ... .

In your Main class you need to add a Token object for each argument. In this example we have three Tokens: the number of lines, the verbosity mode and the input files. In addition, you need to add an ApplicationSettings object. This object is used to contain all the arguments.

The source code for these settings is shown in Listing 1. I first declare the sm_main variable and then the three Token variables: sm_verbose, sm_files, sm_lines. The arguments in the constructor of each token object fully describe the expected usage of the Token:

  • Is it a switch or an argument?
  • What is the switch's name (e.g., -v)?
  • What is its type (integer, string, etc.)?
  • Can it appear multiple times (e.g., -l, 1, -l, 2)?
  • Is it a required argument?
  • If not, when the argument is missing:
    1. Is there an environment variable to provide the value?
    2. Is there a default value?

    A static initializer adds the Token variables to the ApplicationSettings variable. By the time the main() function of your application is reached, the ApplicationSettings object knows everything about the syntax of your command line utility.

    Listing 2 shows the main program of my example. The first line after the try statement calls the parseArgs() method of the ApplicationSettings object. The actual command line arguments are passed as an argument to the object. When the syntax is incorrect, a usage message is printed and an exception is thrown. Otherwise, the Token objects are set to contain appropriate values. For instance, when the -v option is present, the sm_verbose object will be set. Later, when its getValue() method is called, it will return true.

    In a similar fashion, if two files are passed as arguments, let's say and, the sm_files Token will be set appropriately. Its getValue(0) method will return, its getValue(1) method will return

    Now compile the example with your favorite development environment and run the resulting code without passing any arguments. You should get the usage message in Listing 3. But wait a minute: you never wrote code to print usage messages; what's going on here? It's very simple. The framework uses the same code that defines the expected Tokens to generate usage statements. Kiss the ugly, always-out-of-date, static String statements that describe the usage of the utility goodbye.

    Now let's run the program again with some decent arguments. Let's say we run it with arguments "-v". The program prints the arguments correctly. Though we didn't pass any value for the -l switch, the Token returns 0. This is the expected behavior because the default value of the sm_lines Token is indeed 0.

    Why Use the Framework?
    By now some of the advantages of the framework should be obvious to you. The error-prone while and switch statements that usually parse the arguments have been replaced by a few very readable statements.

    These statements:

  • Document the usage of the command line utility
  • Encapsulate the settings so they can be used by the rest of the program
  • Automatically generate usage messages when the user enters incorrect syntax:
    1. Missing arguments
    2. Unexpected arguments
    3. Wrong types of arguments

    The stated advantages speed up the original development of any command line utility. They allow the developer to jump to the real code as soon as possible. At the same time, they provide immediate access to the command line settings and usage messages.

    Where the framework really shines is in the area where most of a developer's time is spent: software maintenance. If a command line utility is successful, users will ask for changes and improvements. Many of them will translate to more command line options or change the syntax of existing ones. The framework makes adding and modifying options trivial and safe. Compile-time messages will save the developer from runtime embarrassment.

    Finally, the framework is extensible. One can define new types of switches that accommodate new data types or anything else a developer desires.

    At this point you can go ahead, download the code and start using it in your own applications. The next few sections discuss the design of the framework.

    The StringArrayIterator Class
    The StringArrayIterator class is a utility class (see Listing 4). It encapsulates an array of strings and a position inside the array. The get() method returns the String at the current position. The moveNext() operation on the array allows the programmer to advance the current position to the next string. The EOF() operation determines when the end of the array has been reached.

    The ApplicationSettings object contains a StringArrayIterator object. It gets initialized from the command line arguments.

    The Token Class
    The Token class, shown in Listing 5, is an abstract class. Each Token object contains a description of an argument or a switch. After a successful parsing it also contains the value or values that were provided for the argument in the command line.

    During the parsing phase, the most important methods of the Token class are the parseSwitch() and parseArgument() methods. Both of them take the StringArrayIterator object with the command line arguments as input. If the current command line argument is recognized, three things occur: it's parsed, the pointer of the StringArrayIterator object is moved and a value of true is returned. If it's not recognized, a value of false is returned.

    The values that correspond to this switch or argument are stored in a Vector of objects. Subclasses determine their class. For instance, the StringToken subclass will have String objects, and the IntegerToken subclass will contain Integer objects.

    While the program is running, the values are accessible using the getValue(int) and getValue() operations.

    Token Subclasses
    A Token subclass encapsulates arguments of a specific type. For example, there's a StringToken, an IntegerToken, etc. Since most of its methods have a generic implementation, each Token subclass has very few methods to implement.

    Listing 6 presents the implementation for the class StringToken. A few more subclasses are provided in the downloaded code. You can extend the framework by implementing more subclasses.

    The ApplicationSettings Object
    The ApplicationSettings object puts everything I've discussed so far together (see Listing 7). It contains all the Token objects and initiates the parsing algorithm. The user triggers the parsing by calling the parseArgs() method.

    The command line arguments are assigned to the StringArrayIterator member of the class. Then, for every command line argument, each Token object is called and asked to parse it as either an option or an argument.

    If no Token object can parse the argument, a usage message is printed by iterating through the Tokens and calling their printUsage() and printUsageExtended() methods. Both methods take an OutputStream as an argument. They print their output to this stream.

    Pure Java and Impurities
    Almost all the code is pure Java. Since pure Java doesn't provide support for environment variables and assertions, I had to use the functions provided in my environment, the Win32 Virtual Machine.

    These few lines of code are carefully isolated in the file shown in Listing 8. In a pure Java environment you can comment out three lines of code from this file. You don't get assertions and support for initialization of arguments from environment variables. Otherwise, everything else works as advertised.

    The framework doesn't provide support for complex scenarios. For instance, there's no support for switches that depend on each other. You can't dictate that the -t option can appear if and only if the -p option appears. You'd have to implement such checks yourself after the arguments were parsed.

    In this article I presented an extensible Java framework. The framework simplifies the development and maintenance of code that parses the arguments of command line utilities and tools.

    The framework doesn't provide support for complex scenarios. Still, my experience is that the framework covers most common cases. I expect that it will be as useful for Java development as it has been for C++.

    P. Kougiouris (1997). "Yet Another Command-Line Parser." C/C++ Users Journal, Vol. 15, No. 4, April.

  • More Stories By Panos Kougiouris

    Panos Kougiouris has ten years' experience in software development for high-tech companies. For the past three years he has been at Healtheon, a Silicon Valley startup, and he has held technical positions with Oracle and Sun Microsystems. Panos holds computer science degrees from the University of Illinois at Urbana-Champaign and the University of Patra, Greece.

    Comments (1) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    Most Recent Comments
    AST 12/04/04 10:52:06 AM EST

    Hi. Just wanted to point out another package for solving this problem. It supports popt-style autohelp as well as POSIX options, joined options (-Wall -Dfoo=bar), repeated options and of course GNU-style (--some-long-option) options.

    Where the library really differs is that it leverages the GoF Command Pattern to make the options "active" in a similar manner to the Swing Action objects. Another feature is the ability to specify which sets of options must be present or cannot be present without requiring coding this logic yourself. The parser does the work for you.

    An article discussing how this can be done at .

    Ok, and yes, I'm a bit biased because I wrote the library... ;)

    Hope this helps,


    @ThingsExpo Stories
    Microservices are a very exciting architectural approach that many organizations are looking to as a way to accelerate innovation. Microservices promise to allow teams to move away from monolithic "ball of mud" systems, but the reality is that, in the vast majority of organizations, different projects and technologies will continue to be developed at different speeds. How to handle the dependencies between these disparate systems with different iteration cycles? Consider the "canoncial problem" in this scenario: microservice A (releases daily) depends on a couple of additions to backend B (re...
    Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Day 2 Keynote at 17th Cloud Expo, Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, wil...
    PubNub has announced the release of BLOCKS, a set of customizable microservices that give developers a simple way to add code and deploy features for realtime apps.PubNub BLOCKS executes business logic directly on the data streaming through PubNub’s network without splitting it off to an intermediary server controlled by the customer. This revolutionary approach streamlines app development, reduces endpoint-to-endpoint latency, and allows apps to better leverage the enormous scalability of PubNub’s Data Stream Network.
    The cloud. Like a comic book superhero, there seems to be no problem it can’t fix or cost it can’t slash. Yet making the transition is not always easy and production environments are still largely on premise. Taking some practical and sensible steps to reduce risk can also help provide a basis for a successful cloud transition. A plethora of surveys from the likes of IDG and Gartner show that more than 70 percent of enterprises have deployed at least one or more cloud application or workload. Yet a closer inspection at the data reveals less than half of these cloud projects involve production...
    Apps and devices shouldn't stop working when there's limited or no network connectivity. Learn how to bring data stored in a cloud database to the edge of the network (and back again) whenever an Internet connection is available. In his session at 17th Cloud Expo, Ben Perlmutter, a Sales Engineer with IBM Cloudant, demonstrated techniques for replicating cloud databases with devices in order to build offline-first mobile or Internet of Things (IoT) apps that can provide a better, faster user experience, both offline and online. The focus of this talk was on IBM Cloudant, Apache CouchDB, and ...
    Container technology is shaping the future of DevOps and it’s also changing the way organizations think about application development. With the rise of mobile applications in the enterprise, businesses are abandoning year-long development cycles and embracing technologies that enable rapid development and continuous deployment of apps. In his session at DevOps Summit, Kurt Collins, Developer Evangelist at, examined how Docker has evolved into a highly effective tool for application delivery by allowing increasingly popular Mobile Backend-as-a-Service (mBaaS) platforms to quickly crea...
    I recently attended and was a speaker at the 4th International Internet of @ThingsExpo at the Santa Clara Convention Center. I also had the opportunity to attend this event last year and I wrote a blog from that show talking about how the “Enterprise Impact of IoT” was a key theme of last year’s show. I was curious to see if the same theme would still resonate 365 days later and what, if any, changes I would see in the content presented.
    Cloud computing delivers on-demand resources that provide businesses with flexibility and cost-savings. The challenge in moving workloads to the cloud has been the cost and complexity of ensuring the initial and ongoing security and regulatory (PCI, HIPAA, FFIEC) compliance across private and public clouds. Manual security compliance is slow, prone to human error, and represents over 50% of the cost of managing cloud applications. Determining how to automate cloud security compliance is critical to maintaining positive ROI. Raxak Protect is an automated security compliance SaaS platform and ma...
    Internet of @ThingsExpo, taking place June 7-9, 2016 at Javits Center, New York City and Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 18th International @CloudExpo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world and ThingsExpo New York Call for Papers is now open.
    With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York and Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound cha...
    We are rapidly moving to a brave new world of interconnected smart homes, cars, offices and factories known as the Internet of Things (IoT). Sensors and monitoring devices will touch every part of our lives. Let's take a closer look at the Internet of Things. The Internet of Things is a worldwide network of objects and devices connected to the Internet. They are electronics, sensors, software and more. These objects connect to the Internet and can be controlled remotely via apps and programs. Because they can be accessed via the Internet, these devices create a tremendous opportunity to inte...
    Today air travel is a minefield of delays, hassles and customer disappointment. Airlines struggle to revitalize the experience. GE and M2Mi will demonstrate practical examples of how IoT solutions are helping airlines bring back personalization, reduce trip time and improve reliability. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Dr. Sarah Cooper, M2Mi’s VP Business Development and Engineering, explored the IoT cloud-based platform technologies driving this change including privacy controls, data transparency and integration of real time context with p...
    We all know that data growth is exploding and storage budgets are shrinking. Instead of showing you charts on about how much data there is, in his General Session at 17th Cloud Expo, Scott Cleland, Senior Director of Product Marketing at HGST, showed how to capture all of your data in one place. After you have your data under control, you can then analyze it in one place, saving time and resources.
    The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
    Just over a week ago I received a long and loud sustained applause for a presentation I delivered at this year’s Cloud Expo in Santa Clara. I was extremely pleased with the turnout and had some very good conversations with many of the attendees. Over the next few days I had many more meaningful conversations and was not only happy with the results but also learned a few new things. Here is everything I learned in those three days distilled into three short points.
    DevOps is about increasing efficiency, but nothing is more inefficient than building the same application twice. However, this is a routine occurrence with enterprise applications that need both a rich desktop web interface and strong mobile support. With recent technological advances from Isomorphic Software and others, rich desktop and tuned mobile experiences can now be created with a single codebase – without compromising functionality, performance or usability. In his session at DevOps Summit, Charles Kendrick, CTO and Chief Architect at Isomorphic Software, demonstrated examples of com...
    As organizations realize the scope of the Internet of Things, gaining key insights from Big Data, through the use of advanced analytics, becomes crucial. However, IoT also creates the need for petabyte scale storage of data from millions of devices. A new type of Storage is required which seamlessly integrates robust data analytics with massive scale. These storage systems will act as “smart systems” provide in-place analytics that speed discovery and enable businesses to quickly derive meaningful and actionable insights. In his session at @ThingsExpo, Paul Turner, Chief Marketing Officer at...
    In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
    In his General Session at 17th Cloud Expo, Bruce Swann, Senior Product Marketing Manager for Adobe Campaign, explored the key ingredients of cross-channel marketing in a digital world. Learn how the Adobe Marketing Cloud can help marketers embrace opportunities for personalized, relevant and real-time customer engagement across offline (direct mail, point of sale, call center) and digital (email, website, SMS, mobile apps, social networks, connected objects).
    The Internet of Everything is re-shaping technology trends–moving away from “request/response” architecture to an “always-on” Streaming Web where data is in constant motion and secure, reliable communication is an absolute necessity. As more and more THINGS go online, the challenges that developers will need to address will only increase exponentially. In his session at @ThingsExpo, Todd Greene, Founder & CEO of PubNub, exploreed the current state of IoT connectivity and review key trends and technology requirements that will drive the Internet of Things from hype to reality.