In Java, the System.getenv() returns an unmodifiable string Map view of the current system environment.

  Map<String, String> env = System.getenv();

  // get PATH environment variable
  String path = System.getenv("PATH");

1. Get a specified environment variable

1.1 Below example uses System.getenv to get the JAVA_HOME environment variable.

SystemEnv.java

package com.favtuts.system;

public class SystemEnv {

    public static void main(String[] args) {
        
        // get a environment variable
        String java_home = System.getenv("JAVA_HOME");
        System.out.println(java_home);        
    }
    
}

Output

/usr/lib/jvm/java-11-openjdk-amd64

1.2 If a requested environment variable is not defined, the System.getenv will return a null.

  String java_home = System.getenv("JAVA_HOME");

  if (java_home == null) {
      System.err.println("JAVA_HOME environment variable is not defined!");
  } else {
      System.out.println(java_home);
  }

1.3 Java 8, Optional example to handle the null.

  String JAVA_HOME =
          Optional.ofNullable(System.getenv("JAVA_HOME1"))
                  .orElseThrow(
                          () -> new IllegalArgumentException("Please defined JAVA_HOME environment variable."));

2. UnsupportedOperationException

The System.getenv() returns an unmodifiable string Map, modify the Map will cause UnsupportedOperationException.

SystemEnv.java

package com.favtuts.system;

import java.util.Map;

public class SystemEnv {

    public static void main(String[] args) {                

        // Unmodifiable the map of environment variables        
        Map<String, String> env = System.getenv();

        // throws UnsupportedOperationException
        env.put("CUSTOM_JAVA_HOME", "/opt/java99/");
    }
    
}

Output

Exception in thread "main" java.lang.UnsupportedOperationException
        at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
        at com.favtuts.system.SystemEnv.main(SystemEnv.java:30)

3. Display all environment variables

The below example will print out all the available system environment variables.

SystemEnv.java

package com.favtuts.system;

import java.util.Map;

public class SystemEnv {

    public static void main(String[] args) {
                       
        Map<String, String> env = System.getenv();

        // Display all environment variables 
        // Java 8
        env.forEach((k, v) -> System.out.println(k + ":" + v));

        // Classic way to loop a map        
        for (Map.Entry<String, String> entry : env.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
    
}

Output

HOME:/home/tvt
PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
JAVA_HOME:/usr/lib/jvm/java-11-openjdk-amd64
PWD:/home/tvt/favtuts/java-core-tutorials-examples

4. Sort the environment variables

The below example will sort and display the environment variables in alphabetical order.

SystemEnv.java

package com.favtuts.system;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class SystemEnv {

    public static void main(String[] args) {
                  
        Map<String, String> env = System.getenv();        
        
        // sort and display the environment variables in alphabetical order
        LinkedHashMap<String, String> collect =
                env.entrySet().stream()
                        .sorted(Map.Entry.comparingByKey())
                        .collect(
                                Collectors.toMap(
                                        Map.Entry::getKey,
                                        Map.Entry::getValue,
                                        (oldValue, newValue) -> oldValue,
                                        LinkedHashMap::new)
                        );

        collect.forEach((k, v) -> System.out.println(k + ":" + v));
    }    
}

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-misc/system

References

Leave a Reply

Your email address will not be published. Required fields are marked *