Environment variables
suggest changeEvery process gets a set of NAME=value strings from its parent: the environment. Shells, containers, CI systems and process managers (systemd, Kubernetes, Docker) all use it to pass configuration to programs. That makes environment variables the standard way to tell a Java service which database to use, which port to listen on, or which API key to send. This approach is the "config" factor of the Twelve-Factor App.
Java gives read-only access to the environment through System.getenv(), and lets you build a new environment for child processes through ProcessBuilder. This article covers both, plus defaults, type conversion, a small config class, how environment variables compare to system properties, .env files, secrets, and testing.
Reading a variable
System.getenv(String) returns the value, or null if the variable is not set:
public class Hello {
public static void main(String[] args) {
String home = System.getenv("HOME");
String missing = System.getenv("DOES_NOT_EXIST");
System.out.println("HOME = " + home);
System.out.println("DOES_NOT_EXIST = " + missing);
}
}
$ java Hello.java
HOME = /home/alice
DOES_NOT_EXIST = null
Since Java 11 you can run a single source file directly with java Hello.java, which is handy for trying out the examples in this article.
Set a variable for a single run in a Unix shell by putting it before the command:
$ GREETING=hi java Hello.java
The PowerShell equivalent is $env:GREETING = "hi"; java Hello.java. In cmd.exe it is set GREETING=hi followed by java Hello.java.
Listing all variables
System.getenv() with no arguments returns an unmodifiable Map<String, String> of the whole environment. The map has no particular order, so copy it into a TreeMap to sort it:
import java.util.Map;
import java.util.TreeMap;
public class ListEnv {
public static void main(String[] args) {
Map<String, String> env = new TreeMap<>(System.getenv());
env.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
HOME=/home/alice
LANG=en_US.UTF-8
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash
USER=alice
...
Trying to change the returned map throws UnsupportedOperationException:
System.getenv().put("FOO", "bar"); // UnsupportedOperationException
You cannot change your own environment
Java has no setenv. The environment is copied when the JVM starts and stays fixed for the life of the process. That is deliberate. Native libraries and other threads may read the C-level environment at any moment, and changing it is not thread-safe.
Old blog posts show reflection hacks that modify the internal map behind System.getenv(). Don't use them. Since Java 16 they fail with InaccessibleObjectException unless you add --add-opens java.base/java.util=ALL-UNNAMED. Even when they work, they only change Java's cached copy, not the real process environment. If you need a different value, pass it in from outside, or design your code so the value can be injected (see the testing section below).
You can choose the environment of a child process, as shown later.
Missing, empty and default values
A variable can be unset (getenv returns null) or set to an empty string (FOO= java App). Most programs should treat both the same way. Give them a default:
String logLevel = System.getenv().getOrDefault("LOG_LEVEL", "info");
getOrDefault only covers the unset case. To treat an empty or whitespace-only value as missing too, write a small helper:
static String env(String name, String defaultValue) {
String v = System.getenv(name);
return (v == null || v.isBlank()) ? defaultValue : v.strip();
}
Optional works well when the value also needs converting:
import java.util.Optional;
int port = Optional.ofNullable(System.getenv("PORT"))
.filter(s -> !s.isBlank())
.map(String::strip)
.map(Integer::parseInt)
.orElse(8080);
For a variable the application cannot run without, fail at startup with a clear message. Don't wait for a NullPointerException deep inside the code:
static String requireEnv(String name) {
String v = System.getenv(name);
if (v == null || v.isBlank()) {
throw new IllegalStateException(
"Required environment variable " + name + " is not set");
}
return v;
}
Exception in thread "main" java.lang.IllegalStateException: Required environment variable DATABASE_URL is not set
at Config.requireEnv(Config.java:41)
at Config.fromEnv(Config.java:18)
at Main.main(Main.java:5)
Parsing typed values
Environment values are always strings. Convert them in one place and include the variable name in error messages. Integer.parseInt("80a") on its own produces an error that doesn't say which setting was wrong.
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
final class Env {
private Env() {}
static int getInt(String name, int def) {
String v = System.getenv(name);
if (v == null || v.isBlank()) return def;
try {
return Integer.parseInt(v.strip());
} catch (NumberFormatException e) {
throw new IllegalStateException(name + " must be an integer, got '" + v + "'", e);
}
}
static boolean getBool(String name, boolean def) {
String v = System.getenv(name);
if (v == null || v.isBlank()) return def;
return switch (v.strip().toLowerCase()) {
case "1", "true", "yes", "on" -> true;
case "0", "false", "no", "off" -> false;
default -> throw new IllegalStateException(
name + " must be true/false, got '" + v + "'");
};
}
/** Accepts ISO-8601 ("PT30S") or a plain number of seconds ("30"). */
static Duration getDuration(String name, Duration def) {
String v = System.getenv(name);
if (v == null || v.isBlank()) return def;
v = v.strip();
return v.chars().allMatch(Character::isDigit)
? Duration.ofSeconds(Long.parseLong(v))
: Duration.parse(v);
}
/** Comma-separated list; empty entries are dropped. */
static List<String> getList(String name) {
String v = System.getenv(name);
if (v == null || v.isBlank()) return List.of();
return Arrays.stream(v.split(","))
.map(String::strip)
.filter(s -> !s.isEmpty())
.toList();
}
}
Don't use Boolean.parseBoolean for flags. It returns false for anything other than "true", so a typo like DEBUG=ture silently turns the flag off.
A configuration record
Read the environment once, at startup, into an immutable object. Pass that object to the code that needs it. The rest of the program never calls System.getenv and is easy to test.
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public record AppConfig(
String databaseUrl,
int port,
boolean debug,
Duration requestTimeout,
List<String> allowedOrigins) {
public static AppConfig fromEnv() {
return from(System::getenv);
}
// Accepts any lookup function, so tests can pass a Map::get.
static AppConfig from(Function<String, String> env) {
return new AppConfig(
require(env, "DATABASE_URL"),
Integer.parseInt(or(env, "PORT", "8080")),
Boolean.parseBoolean(or(env, "DEBUG", "false")),
Duration.ofSeconds(Long.parseLong(or(env, "REQUEST_TIMEOUT_SECONDS", "30"))),
Arrays.stream(or(env, "ALLOWED_ORIGINS", "").split(","))
.map(String::strip).filter(s -> !s.isEmpty()).toList());
}
private static String or(Function<String, String> env, String name, String def) {
String v = env.apply(name);
return (v == null || v.isBlank()) ? def : v.strip();
}
private static String require(Function<String, String> env, String name) {
String v = env.apply(name);
if (v == null || v.isBlank()) {
throw new IllegalStateException(name + " is required");
}
return v;
}
public static void main(String[] args) {
var cfg = from(Map.of(
"DATABASE_URL", "jdbc:postgresql://db/app",
"PORT", "9000",
"ALLOWED_ORIGINS", "https://a.example, https://b.example")::get);
System.out.println(cfg);
}
}
AppConfig[databaseUrl=jdbc:postgresql://db/app, port=9000, debug=false, requestTimeout=PT30S, allowedOrigins=[https://a.example, https://b.example]]
(This short version uses Boolean.parseBoolean to keep the example compact. In real code use the stricter helpers from the previous section.)
Avoid printing a config object that holds passwords or tokens. Records generate a toString() that includes every field. Override toString() to mask secrets.
Environment variables vs. system properties
Java has a second key/value mechanism: system properties, set with -Dname=value on the java command line and read with System.getProperty. See Properties Class and Java Options.
| Environment variables | System properties | |
|---|---|---|
| Set by | parent process, shell, container | -D flag, or System.setProperty |
| Read with | System.getenv(name) |
System.getProperty(name) |
| Mutable at runtime | no | yes |
| Scope | OS-level, inherited by child processes | this JVM only |
| Naming convention | UPPER_SNAKE_CASE |
lower.dotted.case |
| Typical use | deployment config, secrets | JVM/library tuning, local overrides |
The JVM also exposes OS facts as properties. Use them instead of reading platform-specific variables:
System.getProperty("user.home"); // instead of HOME / USERPROFILE
System.getProperty("user.name"); // instead of USER / USERNAME
System.getProperty("java.io.tmpdir"); // instead of TMPDIR / TEMP
System.getProperty("os.name"); // "Linux", "Windows 11", "Mac OS X"
System.lineSeparator(); // "\n" or "\r\n"
A common pattern is to accept both, with the system property taking precedence. That lets a developer override one value with -D without touching the environment:
static String setting(String property, String defaultValue) {
// app.db.url -> APP_DB_URL
String envName = property.toUpperCase().replace('.', '_').replace('-', '_');
String v = System.getProperty(property);
if (v == null) v = System.getenv(envName);
return v != null ? v : defaultValue;
}
// java -Dapp.db.url=jdbc:h2:mem:test App -> uses the property
// APP_DB_URL=jdbc:postgresql://db/app java App -> uses the env var
String url = setting("app.db.url", "jdbc:h2:mem:dev");
Spring Boot applies the same idea ("relaxed binding"): the property spring.datasource.url can be supplied as the environment variable SPRING_DATASOURCE_URL.
Case sensitivity on Windows
On Linux and macOS, names are case-sensitive: Path and PATH are different variables. On Windows they are not. System.getenv(String) follows the platform, so on Windows System.getenv("path") returns the value of Path.
The map returned by System.getenv() is a different story. On Windows it keeps the original spelling of each name and its get is case-sensitive:
// On Windows, where the variable is stored as "Path":
System.getenv("PATH"); // C:\Windows\system32;...
System.getenv("path"); // C:\Windows\system32;...
System.getenv().get("Path"); // C:\Windows\system32;...
System.getenv().get("PATH"); // null on Windows!
To look up a single variable, always use System.getenv(name), not System.getenv().get(name). On every platform, write names in upper case.
Setting the environment of a child process
ProcessBuilder.environment() returns a modifiable copy of the current environment. Changes to it apply only to the processes that builder starts. See also Using the ProcessBuilder class.
import java.io.IOException;
import java.util.Map;
public class ChildEnv {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("sh", "-c", "echo \"$GREETING, $NAME\"; echo HOME=$HOME");
Map<String, String> env = pb.environment();
env.put("GREETING", "Hello");
env.put("NAME", "child");
env.remove("HOME"); // hide a variable from the child
pb.inheritIO();
int exit = pb.start().waitFor();
System.out.println("exit code " + exit);
System.out.println("parent still has HOME=" + System.getenv("HOME"));
}
}
Hello, child
HOME=
exit code 0
parent still has HOME=/home/alice
To start a child with a minimal, predictable environment, for example when running an untrusted tool, clear the map and add back only what is needed:
ProcessBuilder pb = new ProcessBuilder("/usr/bin/env");
Map<String, String> env = pb.environment();
env.clear();
env.put("PATH", "/usr/bin:/bin");
env.put("LANG", "C.UTF-8");
pb.inheritIO().start().waitFor();
PATH=/usr/bin:/bin
LANG=C.UTF-8
The older Runtime.exec(String[] cmd, String[] envp) also takes an environment, as an array of "NAME=value" strings. With envp set, the child gets only those variables. ProcessBuilder is clearer and should be preferred.
The $GREETING above is expanded by sh, not by Java. Java never expands $VAR or %VAR% in command arguments. See Pitfall - Runtime.exec, Process and ProcessBuilder don't understand shell syntax.
Variables the JVM itself reads
A few environment variables configure Java itself rather than your program:
| Variable | Read by | Purpose |
|---|---|---|
JAVA_HOME |
build tools, scripts (not the JVM) | location of the JDK |
CLASSPATH |
java, javac |
default class path when -cp is not given |
JAVA_TOOL_OPTIONS |
every JVM, including embedded ones | extra JVM options; the JVM prints Picked up JAVA_TOOL_OPTIONS: ... |
JDK_JAVA_OPTIONS |
the java launcher only (Java 9+) |
extra options prepended to the command line |
_JAVA_OPTIONS |
HotSpot (undocumented) | like JAVA_TOOL_OPTIONS, but takes precedence; avoid |
JDK_JAVA_OPTIONS is the usual way to add flags in a container without rewriting the entrypoint:
$ docker run -e JDK_JAVA_OPTIONS="-XX:MaxRAMPercentage=75 -Duser.timezone=UTC" myapp
NOTE: Picked up JDK_JAVA_OPTIONS: -XX:MaxRAMPercentage=75 -Duser.timezone=UTC
.env files for local development
In production the platform sets the variables. On a developer machine it is convenient to keep them in a .env file. Add that file to .gitignore so it is never committed:
# .env
DATABASE_URL=jdbc:postgresql://localhost:5432/app
DATABASE_PASSWORD=devpassword
PORT=8080
Java does not read .env files. The dotenv-java library does:
<dependency>
<groupId>io.github.cdimascio</groupId>
<artifactId>dotenv-java</artifactId>
<version>3.2.0</version>
</dependency>
import io.github.cdimascio.dotenv.Dotenv;
Dotenv dotenv = Dotenv.configure()
.ignoreIfMissing() // fine in production, where there is no .env
.load();
String url = dotenv.get("DATABASE_URL"); // checks real env vars first, then .env
String port = dotenv.get("PORT", "8080");
Real environment variables take precedence over values in the file. A deployment can therefore override anything without editing it. dotenv-java does not modify System.getenv(); values are only visible through the Dotenv object. If other libraries read System.getenv directly, set the variables in your IDE run configuration instead, or with set -a; source .env; set +a in the shell before starting the JVM.
Secrets
Environment variables are a common way to deliver secrets, but they are not very secret:
- On Linux, any process running as the same user (and root) can read
/proc/<pid>/environ. Tools likeps ewwshow the environment too. - Child processes inherit everything unless you remove it from
ProcessBuilder.environment(). - Crash reports, debug endpoints (e.g. Spring Boot's
/actuator/env) and carelessSystem.getenv()dumps can leak them into logs.
Reasonable precautions:
// Never log the raw value.
static String mask(String secret) {
if (secret == null || secret.length() < 8) return "****";
return secret.substring(0, 2) + "****" + secret.substring(secret.length() - 2);
}
System.out.println("API key: " + mask(System.getenv("API_KEY"))); // API key: sk****9f
Many platforms (Docker and Kubernetes secrets, systemd credentials) prefer to mount secrets as files. A widespread convention is to support NAME_FILE next to NAME:
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
static String secret(String name) {
String file = System.getenv(name + "_FILE");
if (file != null && !file.isBlank()) {
try {
return Files.readString(Path.of(file)).strip();
} catch (IOException e) {
throw new UncheckedIOException("Cannot read " + name + "_FILE=" + file, e);
}
}
return System.getenv(name);
}
// DATABASE_PASSWORD_FILE=/run/secrets/db_password or DATABASE_PASSWORD=...
String dbPassword = secret("DATABASE_PASSWORD");
Testing code that reads the environment
Because the JVM's environment is fixed, the cleanest approach is to not call System.getenv in the code under test. Read it through a Function<String, String> or Map<String, String> parameter, as AppConfig.from does above. Tests then pass a plain map:
import static org.junit.jupiter.api.Assertions.*;
import java.util.Map;
import org.junit.jupiter.api.Test;
class AppConfigTest {
@Test
void usesDefaults() {
var cfg = AppConfig.from(Map.of("DATABASE_URL", "jdbc:h2:mem:test")::get);
assertEquals(8080, cfg.port());
assertFalse(cfg.debug());
}
@Test
void failsWithoutDatabaseUrl() {
var e = assertThrows(IllegalStateException.class,
() -> AppConfig.from(Map.<String, String>of()::get));
assertEquals("DATABASE_URL is required", e.getMessage());
}
}
Libraries such as System Stubs (uk.org.webcompere:system-stubs-jupiter) and JUnit Pioneer (@SetEnvironmentVariable) can fake variables for code you can't change. They rely on reflection into JDK internals. On recent JDKs they need --add-opens java.base/java.util=ALL-UNNAMED (and java.lang for some versions) in the Surefire/Gradle test JVM arguments. They also change global state, so don't run those tests in parallel. See Unit Testing for general JUnit setup.
For a full integration test, start the application as a child process with ProcessBuilder and a chosen environment.
Character encoding
On Windows the environment is stored as UTF-16 and Java reads it without loss. On Unix-like systems variables are raw bytes. The JVM decodes them using the platform's native encoding (the sun.jnu.encoding property, derived from LANG/LC_ALL). If the process starts with LANG=C or POSIX, non-ASCII values can turn into ?. Containers often have no locale set. Set LANG=C.UTF-8 (or another UTF-8 locale) in the image if variables may contain non-ASCII text. Note that -Dfile.encoding=UTF-8, the default since Java 18, does not affect how the environment is decoded. See Character encoding.
Summary
System.getenv(name)returns the value ornull;System.getenv()returns an unmodifiable map of all variables.- A running JVM cannot change its own environment. Set variables before starting it, or for child processes via
ProcessBuilder.environment(). - Read configuration once at startup into an immutable object. Treat unset and blank values alike, give sensible defaults, and fail fast with the variable name when a required value is missing or malformed.
- Use system properties (
-D) for JVM tuning and local overrides. Supporting both, with properties taking precedence, gives the most flexibility. - On Windows, use
System.getenv(name)rather thanSystem.getenv().get(name), because only the former ignores case. - Keep
.envfiles out of version control. Never log secret values, and consider*_FILEvariables for secrets. - Make code testable by passing an environment lookup function instead of calling
System.getenveverywhere.