Set default value, if exist in use that, if overridden on command line use that

Untested code (just thinking out loud), but I’m thinking there must be a more elegant way to do this.

So there’s three ways to set a variable:

  1. just assign it
  2. read it from a properties file (might not be there)
  3. read it from the command line (could be more than one argument or none)

Higher number takes precedence. How would I approach this?

public static final String APP_DOWNLOAD_PATH;


// If download path is not defined in, set it to the app dir.
String download = properties.getProperty("download", System.getProperty("user.dir"));

// Override if download path is set via command line.
String override = null;
try {
  override = System.getProperty("download");
} catch (NullPointerException | IllegalArgumentException ok) {
  // property is either not found or empty.
String APP_DOWNLOAD_PATH = (override == null || override.isEmpty()) ? download : override;

E: Added restrictions.


The straight forward approach is the best in my opinion. For example:

public static final String APP_DOWNLOAD_PATH = "foo";

public static void main(String... args) {

    String dwnPath = null;
    if(args.length > 0) {
        dwnPath = args[0];
    } else if(System.getProperty("download") != null) { // don't need try-catch, "download" is not null and not empty ("")
        // not DRY at all
        dwnPath = System.getProperty("download");
    } else {
        dwnPath = APP_DOWNLOAD_PATH;

    // rest of program

The above could also be extracted to it’s own function leading to a one liner:

String dwnPath = getDownloadPath(args, System.getProperty("download"), APP_DOWNLOAD_PATH);

The extracted function can also be more elegant than the code above:

/** Documentation */
public static String getDownloadPath(String[] args, String property, String default) {
    return (args.length > 0) ? args[0] : (property != null) ? property : default;