How do I get environment variables?

Environment variables are a set of dynamic values that can affect a running process, such as our Java program. Each process usually have their own copy of these variables.

Now we would like to obtain the available variables in our environment or operating system, how do I do this in Java? Here is a code example of it.

package org.kodejava.lang;

import java.util.Map;
import java.util.Set;

public class SystemEnv {
    public static void main(String[] args) {
        // We get the environment information from the System class. 
        // The getenv method (why shouldn't it called getEnv()?) 
        // returns a map that will never have null keys or values 
        // returned.
        Map<String, String> map = System.getenv();

        Set<String> keys = map.keySet();
        for (String key : keys) {
            // Here we iterate based on the keys inside the map, and
            // with the key in hand we can get it values.
            String value = map.get(key);
            System.out.println(key + " = " + value);
        }
    }
}

Here are some results on my machine.

...
M2 = C:\ProgramData\chocolatey\lib\maven\apache-maven-3.5.0\bin
JETTY_HOME = C:\ProgramData\chocolatey\lib\jetty\tools\jetty-distribution-9.4.31.v20200723
USERNAME = wsaryada
ProgramFiles(x86) = C:\Program Files (x86)
M2_REPO = C:\Users\wsaryada\.m2
SPRING_HOME = C:\ProgramData\chocolatey\lib\spring-boot-cli\spring-2.2.4.RELEASE
M2_HOME = C:\ProgramData\chocolatey\lib\maven\apache-maven-3.5.0
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_161
OS = Windows_NT
COMPUTERNAME = KRAKATAU
CATALINA_HOME = C:\tools\apache-tomcat-10.0.11
...
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.