Java
Environment Variables
Programming
Code Implementation
Java Development

How do I set environment variables from Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Java can read environment variables for the current process, but it cannot reliably change the operating system environment of the parent shell or other already-running processes. In practice, the correct options are to read variables with System.getenv, pass environment variables to child processes with ProcessBuilder, or use a normal application configuration system instead of treating environment variables as mutable application state.

Read Environment Variables from Java

If your goal is to consume environment variables that were already provided by the shell, service manager, Docker, or Kubernetes, use System.getenv.

java
1public class ReadEnvExample {
2    public static void main(String[] args) {
3        String javaHome = System.getenv("JAVA_HOME");
4        String appEnv = System.getenv("APP_ENV");
5
6        System.out.println("JAVA_HOME = " + javaHome);
7        System.out.println("APP_ENV = " + appEnv);
8    }
9}

This is the normal model for deployment-time configuration such as database hosts, feature flags, and credentials injected by the platform.

Know What Java Cannot Do

A common misunderstanding is expecting a Java program to permanently change the environment of the terminal that launched it. That is not how process environments work. A child process inherits a copy of the parent environment. The child cannot mutate the parent copy and send the change back upward.

So if a Java program appears to set an environment variable and then exits, the original shell session still has the old environment. That is a process model rule, not just a missing Java API.

Set Environment Variables for Child Processes

What Java can do is launch another process with extra or overridden environment variables. ProcessBuilder is the standard mechanism.

java
1import java.io.BufferedReader;
2import java.io.InputStreamReader;
3import java.util.Map;
4
5public class ChildProcessEnvExample {
6    public static void main(String[] args) throws Exception {
7        ProcessBuilder builder = new ProcessBuilder("sh", "-c", "echo $GREETING");
8        Map<String, String> env = builder.environment();
9        env.put("GREETING", "hello-from-java");
10
11        Process process = builder.start();
12
13        try (BufferedReader reader = new BufferedReader(
14                new InputStreamReader(process.getInputStream()))) {
15            String line;
16            while ((line = reader.readLine()) != null) {
17                System.out.println(line);
18            }
19        }
20
21        int exitCode = process.waitFor();
22        System.out.println("Exit code: " + exitCode);
23    }
24}

That is the right pattern when your Java application launches scripts, CLI tools, or subprocess-based workflows.

Prefer Explicit Application Configuration

If the real goal is simply to configure your Java application, environment variables are only one option. A dedicated configuration class is often clearer than scattered System.getenv calls.

java
1public final class AppConfig {
2    private final String host;
3    private final int port;
4
5    public AppConfig() {
6        this.host = requireEnv("APP_HOST");
7        this.port = Integer.parseInt(requireEnv("APP_PORT"));
8    }
9
10    private static String requireEnv(String name) {
11        String value = System.getenv(name);
12        if (value == null || value.isBlank()) {
13            throw new IllegalStateException("Missing environment variable: " + name);
14        }
15        return value;
16    }
17
18    public String getHost() {
19        return host;
20    }
21
22    public int getPort() {
23        return port;
24    }
25}

This approach centralizes validation and makes missing configuration fail early.

Make Environment Access Testable

Direct System.getenv calls scattered everywhere are awkward to test. A simple wrapper makes the code easier to reason about and unit test.

java
1import java.util.Map;
2
3public class EnvReader {
4    private final Map<String, String> env;
5
6    public EnvReader(Map<String, String> env) {
7        this.env = env;
8    }
9
10    public String require(String key) {
11        String value = env.get(key);
12        if (value == null || value.isBlank()) {
13            throw new IllegalArgumentException("Missing key: " + key);
14        }
15        return value;
16    }
17}

Now tests can pass a normal Map instead of depending on the real process environment.

Common Pitfalls

  • Expecting Java to permanently modify the environment of the shell or service that launched it is a process-model misunderstanding.
  • Using environment variables as mutable application state instead of as startup configuration makes behavior harder to reason about.
  • Calling System.getenv all over the codebase spreads hidden dependencies and weakens validation.
  • Forgetting that child processes receive a copied environment leads to incorrect assumptions about shared state.
  • Failing to validate required variables turns configuration mistakes into confusing runtime failures later.

Summary

  • Java can read environment variables with System.getenv.
  • Java cannot safely update the parent process environment.
  • Use ProcessBuilder.environment() when you need to set variables for child processes.
  • Centralize environment-based configuration so validation and testing stay manageable.
  • Treat environment variables as startup inputs, not as general-purpose mutable state.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.