Environment Variables in CLIPS

Our first program will demonstrate 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
        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 null.

$ java EnvironmentVariables
FOO: null
BAR: null

JAVA_HOME
PATH
USER
...

Note that System.setProperty() doesn’t actually modify the system environment variables, it only sets Java system properties. To see the effect of setting an environment variable, you need to set it before running the Java program:

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

The list of environment variables will depend on your particular machine.

In Java, unlike in some other languages, you cannot modify the environment variables of the currently running process. The System.setProperty() method sets a Java system property, which is different from an environment variable. If you need to modify environment variables, you typically do so before starting the Java program, or you use system properties as an alternative within your Java application.