System.getenv()
Returns the value of an environment variable, or null if it is not set.
Available since: Java 1.0
Syntax
public static String getenv(String name)Parameters
| Parameter | Type | Description |
|---|---|---|
| name | String | The variable name, for example PATH or APP_MODE. |
Return value
StringThe variable value, or null.
Examples
The variable is set when the program starts. On Linux and macOS: APP_MODE=production java Main.java, in PowerShell first run $env:APP_MODE = "production":
void main() {
String mode = System.getenv("APP_MODE");
IO.println("Mode: " + mode);
}Output:
Mode: productionIf the variable is missing, the method returns null — substitute a default value:
void main() {
String port = System.getenv("APP_PORT");
IO.println(port);
int value = port != null ? Integer.parseInt(port) : 8080;
IO.println(value);
}Output:
null
8080Notes
Environment variables are set by the system or by whoever starts the program; Java can only read them. On Windows the names are case-insensitive, on Linux and macOS they are case-sensitive. Without an argument System.getenv() returns an unmodifiable Map with all variables. A short way to give a default is Objects.requireNonNullElse(System.getenv("APP_PORT"), "8080"). Passwords and API keys are usually passed through environment variables rather than written in the code.
See also
- System.getProperty() — Returns a JVM system property: the Java version, the OS name, or your own property set with -D.
- System.exit() — Terminates the program immediately with the given exit code.
- Objects.requireNonNull() — Checks that a value is not null and throws NullPointerException with a clear message right away.
- Map.getOrDefault() — Returns the value for a key, or a fallback when the key is absent.
Related recipes
In the tutorial
- Arguments, environment and exit codes — How a Java program gets settings from outside — command-line arguments, environment variables with System.getenv, system properties with System.getProperty and -D, and exit codes with System.exit.