Environment Variables in Java

Our program demonstrates how to work with environment variables in Java. Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables.

import java.util.Map;

public class EnvironmentVariables {
    public static void main(String[] args) {
        // To set a key/value pair, use System.setProperty
        // To get a value for a key, use System.getenv
        // System.getenv will return null if the key isn't present in the environment
        System.setProperty("FOO", "1");
        System.out.println("FOO: " + System.getenv("FOO"));
        System.out.println("BAR: " + System.getenv("BAR"));

        // Use System.getenv() to get all environment variables
        // This returns a Map<String, String> of all key/value pairs in the environment
        System.out.println();
        Map<String, String> env = System.getenv();
        for (String key : env.keySet()) {
            System.out.println(key);
        }
    }
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ java EnvironmentVariables
FOO: null
BAR: null

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 java EnvironmentVariables
FOO: null
BAR: 2
...

Note that in Java, System.setProperty() sets a system property, not an environment variable. Environment variables are typically set outside of the Java program and accessed using System.getenv(). The System.getenv() method cannot modify the environment variables of the current process.