Check these out:

  • http://commons.apache.org/cli/
  • http://www.martiansoftware.com/jsap/

Or roll your own:

  • http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

For instance, this is how you use commons-cli to parse 2 string arguments:

import org.apache.commons.cli.*;

public class Main {


    public static void main(String[] args) throws Exception {

        Options options = new Options();

        Option input = new Option("i", "input", true, "input file path");
        input.setRequired(true);
        options.addOption(input);

        Option output = new Option("o", "output", true, "output file");
        output.setRequired(true);
        options.addOption(output);

        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();
        CommandLine cmd = null;//not a good practice, it serves it purpose 

        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
            formatter.printHelp("utility-name", options);

            System.exit(1);
        }

        String inputFilePath = cmd.getOptionValue("input");
        String outputFilePath = cmd.getOptionValue("output");

        System.out.println(inputFilePath);
        System.out.println(outputFilePath);

    }

}

usage from command line:

$> java -jar target/my-utility.jar -i asd                                                                                       
Missing required option: o

usage: utility-name
 -i,--input <arg>    input file path
 -o,--output <arg>   output file
Answer from Vinko Vrsalovic on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › environment › cmdLineArgs.html
Command-Line Arguments (The Java™ Tutorials > Essential Java Classes > The Platform Environment)
Here is a code snippet that converts ... System.err.println("Argument" + args[0] + " must be an integer."); System.exit(1); } } parseInt throws a NumberFormatException if the format of args[0] isn't valid....
Discussions

Parse cmd line arguments to your java utilities with Args4J
What does it offer that: http://commons.apache.org/proper/commons-cli/ doesn't? More on reddit.com
🌐 r/java
7
5
June 3, 2015
gratis - Command-line option parser for Java - Software Recommendations Stack Exchange
I'm writing a shell in Java because ... in Java for far too long and I've forgotten a lot of it. I was going to write my own, but right now I'd like to get a working prototype, so I would like to drop in an existing command-line option parser. ... Takes an arbitrary String or String[] (i.e. doesn't use the arguments from the command ... More on softwarerecs.stackexchange.com
🌐 softwarerecs.stackexchange.com
December 2, 2015
How to manually parse command line arguments?
There’s been a great deal of discussion over the years about passing command line arguments to tests with Gradle (IE: -Dfoo=bar). The solutions generally boil down to two approaches: Adding a check for every supported… More on discuss.gradle.org
🌐 discuss.gradle.org
5
0
November 5, 2015
Is there a static method to get command-line arguments?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
10
2
February 27, 2024
🌐
GitHub
github.com › timtiemens › javacommandlineparser
GitHub - timtiemens/javacommandlineparser: Taxonomy of Java Command Line Parser Libraries · GitHub
Below is a table showing Java command-line parsing libraries, sorted by name. "Rank" is my rank for the library (1 to 4, or blank). "Annotation" indicates the library uses Java annotations for argument metadata (i.e. "good"). "KeyValue" indicates that the library uses Java map structures to store and access the arguments (i.e.
Author   timtiemens
🌐
Apache Commons
commons.apache.org › proper › commons-cli › javadocs › api-1.3 › org › apache › commons › cli › CommandLineParser.html
CommandLineParser (Apache Commons CLI 1.3 API)
Parse the arguments according to the specified options. ... ParseException - if there are any problems encountered while parsing the command line tokens.
🌐
Reddit
reddit.com › r/java › parse cmd line arguments to your java utilities with args4j
r/java on Reddit: Parse cmd line arguments to your java utilities with Args4J
June 3, 2015 -

I discovered Args4J a few weeks ago, but just today sat down to add a feature to a flat file parsing and format verification utility that I am writing for work ( referenced here ).

The author, Kohsuke Kawaguchi, is the lead developer of my namesake, Jenkins-ci.

For once, the tutorial and howto for a package is concise, and leaves out all sorts of other dependencies that mainly serve to trip up someone attempting to learn the new thing.

If you write utility programs that need command line argument's parsed, consider checking out Args4J.

🌐
Opensource.com
opensource.com › article › 21 › 8 › java-commons-cli
Parse command options in Java with commons-cli | Opensource.com
August 13, 2021 - Java and the Apache commons make it easy to do. Here's the full demonstration code for your reference: package com.opensource.myapp; import org.apache.commons.cli.*; public class Main { /** * @param args the command line arguments * @throws org.apache.commons.cli.ParseException */ public static void main(String[] args) throws ParseException { // define options Options options = new Options(); Option alpha = new Option("a", "alpha", false, "Activate feature alpha"); options.addOption(alpha); Option config = Option.builder("c").longOpt("config") .argName("config") .hasArg() .required(true) .desc
Find elsewhere
🌐
Argparse4j
argparse4j.github.io
Argparse4j - The Java command-line argument parser library — argparse4j 0.9.0 documentation
Argparse4j is a command line argument parser library for Java based on Python’s argparse module.
Top answer
1 of 4
3

You could check out FeSimpleArgs

I believe it fulfills all your requirements:

Concept: A very light-weight command-line parser. Takes arguments in either a String or String[] form, returns a class instance holding the arguments in a map, and the parameters in a list.

Requirements:

  • Takes an arbitrary String or String[] (i.e. doesn't use the arguments from the command line) Yes
  • Takes arguments in a similar format to getopt (the GNU enhanced version); specifically:
  • Multiple single-letter options can be joined (e.g. -a -b -c to -abc) Yes
  • Supports long options (e.g. --message="Hello!") (though it doesn't have to support single-dash long options) Yes
  • Assumes all non-option-like bits at the end are parameters to be passed normally (e.g. -abc --long="Hello!" param1 param2 tells me that the parameters are param1 and param2) Yes
  • -- can be used to separate options from arguments (e.g. -ab --custom="hello" -- -file_starting_with_hyphen -another gives me the options/flags a, b, and custom with the appropriate values, and tells me that the arguments are -file_starting_with_hyphen and -another) Yes
  • Whitespace can be part of arguments, if it's quoted. Yes
  • An option name followed by a value is parsed as the option having that value (e.g. -h foo says that there is an option, h, with a value, foo) Yes

  • Entirely cross-platform Yes

  • Doesn't need me to specify which options I'm looking for (i.e. I pass it a String or String[] and it tells me which flags/options were set, as opposed to it looking for the options I want to set and assuming the rest are arguments) Yes

as to usage:

  • Free (as in beer) Yes - Apache 2.0
  • Can be legally used in any project (i.e. not noncommercial, not GPL) Yes - Apache 2.0
  • Minimal copyright license (Not copyleft -- I like not worrying about legal issues, and I hate people trying to tell me that I can't use my work, however, I damned well, please) Yes - Apache 2.0

Published under Apache 2.0 license.

Ideal, but not necessary:

  • Small -- one file Yes (one file for the parser, one for the unit tests, not needed to parse)
  • Uses the built-in interfaces (java.util.Map, specifically) to return data. (This is so I can write my own function more easily later) **Sort of ** (Returns a class holding a java.util.Map of arguments and a List of parameters)

USAGE Usage: 1) Construct an instance of FeSimpleArgs

FeSimpleArgs parser = new FeSimpleArgs();

2) Use it to parse your arguments:

FeSimpleArgs.Result result = parser.parse ("-def=value1 --GHI=value2 -a -b -c=value3 -n=\"foo bar baz\" -- param1 -param2"); 

3) Examine your results: From the above, result will consist of a Map containing the following arguments and flags (note that there's no real meaning to "argument" or "flag", I'm just using those terms to separate whether they take values or not - all are in the same Map).

  • a
  • b
  • d
  • e
  • f with value=value1
  • GHI with value=value2
  • c with value=value3
  • n with value=foo bar baz (note quotes are stripped)

And a list containing these parameters (note that the leading hyphen is preserved) - param1 - -param2

4) Profit?

For other examples, please see the included unit tests.

Disclaimer: I am the author of FeSimpleArgs

2 of 4
3

picocli may be of interest. It is a single source file to encourage command line app authors to include it as source as a simpler alternative to shading jars into an uberjar. It also fulfills all other requirements stated in the OP - UPDATE: except for the requirement that options cannot be fixed at compile time :-(.

UPDATE 2: picocli 3.x offers a programmatic API in addition to the annotations API, so now it meets all requirements. Note that Groovy CliBuilder is based on picocli since Groovy 2.5. This is exactly what the OP is asking for: dynamically add options and positional parameters to a command.

It recently added autocompletion functionality.

Another feature you may like is its colorized usage help.

Parser features:

  • Annotation API: parsing is one line of code in your application
  • Programmatic API: everything that is possible with annotations can be done programmatically
  • Strongly typed everything - command line options as well as positional parameters
  • POSIX clustered short options (<command> -xvfInputFile as well as <command> -x -v -f InputFile) and GNU long options
  • An arity model that allows a minimum, maximum and variable number of parameters, e.g, "1..*", "3..5"
  • Subcommands (can be nested to arbitrary depth)
  • Works with Java 5 and higher

The usage help message is easy to customize with annotations (without programming). For example:

(source)

I couldn't resist adding one more screenshot to show what usage help messages are possible. Usage help is the face of your application, so be creative and have fun!

Disclaimer: I created picocli. Feedback or questions very welcome.

🌐
Baeldung
baeldung.com › home › java › core java › command-line arguments in java
Command-Line Arguments in Java | Baeldung
December 27, 2025 - In this short tutorial, we’ll explore how we can handle command-line arguments in Java.
🌐
Medium
medium.com › @AlexanderObregon › processing-command-line-arguments-in-java-applications-200ba9b7f029
Processing Command-Line Arguments in Java Applications
March 14, 2025 - Even if an argument looks like a number or a boolean value, Java does not automatically convert it. Instead, the program must manually parse each argument based on the expected data type.
🌐
Gradle
discuss.gradle.org › help/discuss
How to manually parse command line arguments? - Help/Discuss - Gradle Forums
November 5, 2015 - There’s been a great deal of discussion over the years about passing command line arguments to tests with Gradle (IE: -Dfoo=bar). The solutions generally boil down to two approaches: Adding a check for every supported parameter test { systemProperty "myPropOne", System.getProperty("myPropOne") systemProperty "myPropTwo", System.getProperty("myPropTwo") systemProperty "myPropThree", System.getProperty("myPropThree") // etc...
🌐
Reddit
reddit.com › r/javahelp › is there a static method to get command-line arguments?
r/javahelp on Reddit: Is there a static method to get command-line arguments?
February 27, 2024 -

Is there a static method somewhere that gets command-line arguments? In Go there is os.Args to get command-line arguments, rather than just as arguments to the main method. It is much more elegant, and as a result, I'm wondering if there is a Java equivalent in the form of a static method or static field.

EDIT: To everyone asking how is it more elegant - Imagine you're working on a hobby project, you realized after a week of development that you probably should use command-line arguments to get a value. Now you have to route a String[] called args through 12 different classes and methods. In what world is that anywhere as elegant as a static method?

🌐
DEV Community
dev.to › oshanoshu › simple-java-command-line-argument-parser-implementation-n40
Simple Java Command Line Argument Parser Implementation - DEV Community
February 24, 2021 - You can pass the initial configuration ... via command-line arguments. For example: ## if you want to send file path java MyProgram -filePath file1.txt ## if you want to send multiple file paths java MyProgram -filePath file1.txt file2.txt ## or, if you just want to send flags java MyProgram -noprint · By default, Java takes each string as an argument and cannot differentiate between argument names, values, or flags. So, today, we'll write a simple program that will parse the arguments ...
🌐
Reintech
reintech.io › blog › java-command-line-applications-parsing-processing-arguments
Java command-line applications: Parsing and processing arguments | Reintech media
January 29, 2026 - This guide covers practical approaches to argument parsing in Java, from manual implementations to industry-standard libraries. You'll learn when to use each technique and how to handle edge cases that commonly trip up developers. When you launch a Java application from the command line, the JVM passes all arguments as a String[] array to your main method:
🌐
GeeksforGeeks
geeksforgeeks.org › java › command-line-arguments-in-java
Command Line Arguments in Java - GeeksforGeeks
If no arguments are given (e.g., java GFG), it throws ArrayIndexOutOfBoundsException since args is empty. Command-line arguments in Java are space-separated values passed to the main(String[] args) method.
Published   May 22, 2025
🌐
Quora
quora.com › What-is-the-best-way-to-parse-command-line-arguments-with-Java
What is the best way to parse command-line arguments with Java? - Quora
Answer (1 of 2): First of all it depends in what type you want to parse it. By default, command line arguments are in string type, so you can parse it to int, float double etc. Second how many arguments you are going to pass at command line, that all are stored in agrs[] array. you can access it...
🌐
Blogger
marxsoftware.blogspot.com › 2017 › 07 › parse-cmd.html
Inspired by Actual Events: Java Command-Line Interfaces (Part 9): parse-cmd
The "definition" stage of parsing command-line arguments with parse-cmd is demonstrated in the next (incomplete) code listing. [Note that the example in this post is similar to that used in the previous eight posts in this series.] ... /** String displayed where there is a problem processing arguments. */ private final static String USAGE = "java examples.dustin.commandline.parsecmd.Main --file <filePathAndName> [--verbose 1]"; public static void main(final String[] arguments) { final ParseCmd parseCmd = new ParseCmd.Builder().parm("--file", "") .req() .parm("--verbose", "0") .help(USAGE) .build();
🌐
Whitman College
whitman.edu › mathematics › java_tutorial › java › cmdLineArgs › cmdLineArgs.html
Command Line Arguments
Typically, the user can specify the command line arguments in any order thereby requiring the application to parse them. Note to C and C++ Programmers: The command line arguments passed to a Java application differ in number and in type than those passed to a C or C++ program.