Java System getenv() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 5+

Definition

In Java, System.getenv(name) returns the value of the environment variable name, or null if it is not set. System.getenv() with no argument returns all environment variables as a read-only Map<String, String>.

Environment variables belong to the operating system process: the shell, a container, or a CI server sets them before Java starts (for example PATH, HOME, or DATABASE_URL). They are a popular way to pass configuration and secrets into a program. Java can read them but cannot change them for the running process.

A static method of the java.lang.System class, added in Java 5 (JDK 1.5). Call it on the class name, as in System.getenv(...). No import is needed, because classes in java.lang are always visible.

Syntax

Ask for one variable by name, or get the whole map:

Java
String path = System.getenv("PATH");          // null if not set
Map<String, String> env = System.getenv();    // all variables, read-only
String region = env.getOrDefault("REGION", "eu-west");
CallWhat it does
System.getenv("HOME")One variable; null when it does not exist.
System.getenv()All variables as an unmodifiable Map.
System.getenv().getOrDefault("X", "dflt")A value with a fallback (Java 8+ Map method).
new ProcessBuilder(...).environment()A changeable copy for a child process you start.

getenv(String) existed in very early Java, was deprecated and stopped working for a while, and came back fully in Java 5 together with getenv(). On Windows, names are case-insensitive (Path and PATH are the same); on Linux and macOS they are case-sensitive.

Library declarations
Java
// java.lang.System
public static String getenv(String name)
public static Map<String, String> getenv()

Parameters

ParameterDescription
name(First overload) Name of the variable. Must not be null.

Return Value

Return ValueDescription
String(First overload) The variable's value, or null if it is not defined.
Map<String, String>(Second overload) Every variable name mapped to its value. The map cannot be modified.

Compare with Similar Methods

Environment variables vs other settings:

MethodHow it differs
getProperty(key)Java system properties: set with -D or in code, changeable at run time.
getProperties()All system properties, a completely separate set of names.
ProcessBuilder.environment()Edits the environment of a process you are about to start, not your own.

Java Examples

Example 1 — Handle a Variable That Is Not Set

The names are made up, so they are not set on any computer. A null check turns the missing value into a sensible default.

Java
public class SystemGetenvMissing {
    public static void main(String[] args) {
        String value = System.getenv("CODETOFUN_NOT_SET_12345");
        System.out.println("Variable value: " + value);

        String level = System.getenv("CODETOFUN_LOG_LEVEL_12345");
        if (level == null) {
            level = "INFO";
        }
        System.out.println("Log level: " + level);
        System.out.println("Same name as a property: " + System.getProperty("CODETOFUN_NOT_SET_12345"));
    }
}

How It Works

  1. Unknown means null. getenv never throws for a missing variable; it returns null, which prints as the word null.
  2. Supply a default. The if (level == null) check replaces the missing log level with "INFO", the usual pattern for optional configuration.
  3. Two separate worlds. A system property with the same name is also missing: environment variables and system properties never share values.

Example 2 — Search the Environment Map and Try to Change It

getenv() returns all variables. The map can be searched, but not modified, and a null name is rejected.

Java
import java.util.Map;

public class SystemGetenvMap {
    public static void main(String[] args) {
        Map<String, String> env = System.getenv();
        System.out.println("Has made-up variable: " + env.containsKey("CODETOFUN_NOT_SET_12345"));
        try {
            env.put("CODETOFUN_NEW", "1");
        } catch (UnsupportedOperationException e) {
            System.out.println("put: " + e.getClass().getSimpleName());
        }
        try {
            System.getenv(null);
        } catch (NullPointerException e) {
            System.out.println("getenv(null): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. A snapshot of the process. The map holds the variables the JVM received at startup; the made-up name is not among them, so containsKey is false.
  2. Read-only by design. The map is unmodifiable, so put throws UnsupportedOperationException; Java cannot change its own environment.
  3. Names are required. System.getenv(null) throws NullPointerException instead of returning null.

Example 3 — Read Settings with Defaults and Safe Parsing

getOrDefault gives a text fallback; a helper parses a number and falls back when the variable is missing or invalid.

Java
import java.util.Map;

public class SystemGetenvDefaults {
    static int intSetting(String name, int fallback) {
        String text = System.getenv(name);
        if (text == null) {
            return fallback;
        }
        try {
            return Integer.parseInt(text.trim());
        } catch (NumberFormatException e) {
            return fallback;
        }
    }

    public static void main(String[] args) {
        Map<String, String> env = System.getenv();
        String region = env.getOrDefault("CODETOFUN_REGION_12345", "eu-west");
        int port = intSetting("CODETOFUN_PORT_12345", 8080);

        System.out.println("Region: " + region);
        System.out.println("Port: " + port);
        System.out.println("Next port: " + (port + 1));
    }
}

How It Works

  1. A map method as fallback. getOrDefault (Java 8) returns "eu-west" because the made-up region variable does not exist.
  2. Text to number, carefully. intSetting returns the fallback for a missing variable and also for text such as "80a" that parseInt rejects, so a typo cannot crash the program.
  3. Real numbers afterwards. port is an int 8080, so port + 1 is arithmetic and prints 8081. Setting CODETOFUN_PORT_12345=9000 in the shell would print 9000 and 9001.

Frequently Asked Questions

null. Check for null, or use System.getenv().getOrDefault(name, fallback) to supply a default.
Not for the running JVM: the map from getenv() is read-only. You can set variables for a child process with ProcessBuilder.environment() before starting it.
getenv reads operating system environment variables, set before Java starts. getProperty reads Java system properties, which can come from -D options or setProperty calls.
On Linux and macOS yes. On Windows, getenv(name) ignores case, so getenv("path") and getenv("PATH") return the same value.
Because you tried to change the returned map with put, remove, or clear. The map is unmodifiable.

Next: getLogger()

Get a System.Logger for platform logging with levels such as INFO and DEBUG (Java 9+).

getLogger() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful