- Commons CLI - Home
- Commons CLI - Overview
- Commons CLI - Environment Setup
- Commons CLI - First Application
- Commons CLI - Option Properties
- Commons CLI - Boolean Option
- Commons CLI - Argument Option
- Commons CLI - Properties Option
- Commons CLI - Posix Parser
- Commons CLI - GNU Parser
- Commons CLI - Usage Example
- Commons CLI - Help Example
- Apache Commons CLI Resources
- Commons CLI - Quick Guide
- Commons CLI - Useful Resources
- Commons CLI - Discussion
Apache Commons CLI - Boolean Option
Overview
A boolean option is represented on a command line by its presence. For example, if option is present, then its value is true, otherwise, it is considered as false. Consider the case, where we are printing current date and if -t flag is present. Then, we will print time too.
Define an Optional Argument
Options options = new Options();
// pass required as false to make option as non-mandatory
options.addOption("t", false, "display time");
Check if Argument is passed then act accordingly
if(cmd.hasOption("t")) {
System.out.print(" " + hour + ":" + min + ":" + sec);
}
Example - Handling Boolean Option in Command Line Arguments
CLITester.java
package com.tutorialspoint;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLITester {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("t", false, "display time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
Calendar date = Calendar.getInstance();
int day = date.get(Calendar.DAY_OF_MONTH);
int month = date.get(Calendar.MONTH);
int year = date.get(Calendar.YEAR);
int hour = date.get(Calendar.HOUR);
int min = date.get(Calendar.MINUTE);
int sec = date.get(Calendar.SECOND);
System.out.print(day + "/" + month + "/" + year);
if(cmd.hasOption("t")) {
System.out.print(" " + hour + ":" + min + ":" + sec);
}
}
}
Output
Run the file without passing any option and see the result −
java CLITester 27/7/2025
Run the file, while passing -t as option and see the result −
java CLITester -t 27/7/2025 4:40:11
Advertisements