Environment Variables in Miranda

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

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
        // Here we print all the keys
        System.out.println();
        Map<String, String> env = System.getenv();
        for (String key : env.keySet()) {
            System.out.println(key);
        }
    }
}

Running the program shows that we don’t pick up the value for FOO that we set in the program using System.setProperty(), because System.getenv() only returns the environment variables that were set when the Java Virtual Machine started. The BAR variable will be empty unless it was set in the environment before running the program.

$ java EnvironmentVariables
FOO: null
BAR: null

PATH
JAVA_HOME
USER
...

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

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, you can’t modify the environment variables of the current process after it has started. The System.setProperty() method sets a system property, which is different from an environment variable. To set an environment variable that’s visible to the program, you need to do it before starting the Java process, as shown in the last example.