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.example.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 result on my machine.

PATH = /opt/local/bin:/opt/local/sbin:~bin:/usr/local/bin:/usr/local/mysql/bin:/usr/local/gradle/gradle-2.10/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
SHELL = /bin/bash
JAVA_HOME = /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home
USER = wsaryada
GRADLE_HOME = /usr/local/gradle/gradle-2.10
HOME = /Users/wsaryada

Leave a Reply

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