Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read an environment variable with a default value

Short answer

System.getenv() returns null if the variable is not set — substitute a default with Objects.requireNonNullElse():

void main() {
    String mode = Objects.requireNonNullElse(System.getenv("APP_MODE"), "development");
    IO.println(mode);
}

Output:

development

When the variable is set

The variable is set before starting: on Linux and macOS APP_MODE=production java Main.java, in PowerShell $env:APP_MODE = "production" and then java Main.java:

void main() {
    String mode = Objects.requireNonNullElse(System.getenv("APP_MODE"), "development");
    IO.println(mode);
}

Output:

production

A number from a variable

Environment variables are always strings. Optional is handy for a number:

void main() {
    int port = Optional.ofNullable(System.getenv("APP_PORT"))
        .map(Integer::parseInt)
        .orElse(8080);
    int workers = Optional.ofNullable(System.getenv("APP_WORKERS"))
        .map(Integer::parseInt)
        .orElse(4);
 
    IO.println(port);
    IO.println(workers);
}

Output:

9090
4

A required variable

If the program cannot work without the value, stop right away with a clear message:

void main() {
    String url = System.getenv("DATABASE_URL");
    if (url == null || url.isBlank()) {
        throw new IllegalStateException("Environment variable DATABASE_URL is not set");
    }
    IO.println("Connecting to " + url);
}

Output:

Exception in thread "main" java.lang.IllegalStateException: Environment variable DATABASE_URL is not set

Common mistake

Mixing up environment variables and system properties. A value passed as java -Dapp.mode=test Main.java is read with System.getProperty(), and System.getenv() does not see it:

void main() {
    IO.println(System.getProperty("app.mode"));
    IO.println(System.getenv("app.mode"));
}

Output:

test
null

Functions used in this recipe

  • System.getenv() — Returns the value of an environment variable, or null if it is not set.
  • System.getProperty() — Returns a JVM system property: the Java version, the OS name, or your own property set with -D.
  • Objects.requireNonNull() — Checks that a value is not null and throws NullPointerException with a clear message right away.
  • Optional.ofNullable() — Wraps a value that may be `null` into an `Optional`.

Thanks for reading!

Donate to the site — we work hard for you.