Retrieving environment variables in Java
This section will demonstrate how to retrieve environment variables in Java. The Java library has a built-in class System that can be used to retrieve variables.
Retrieving a single environment variable
To retrieve the value of a specific environment variable, use System.getenv("<key>"). If the variable is set, its value will be returned; otherwise, null is returned.
String home = System.getenv("HOME");
System.out.println(home);
Retrieving all the environment variables
To retrieve all the environment variables and their corresponding values in Java, we can use the System.getenv() method. This method returns an unmodifiable Hashmap containing all the environment variables. We can then iterate through the Hashmap, retrieve each variable's name and its corresponding value, and print them out. The following sample code demonstrates how to retrieve all environment variables using this method.
Map<String, String> env = System.getenv();
env.forEach((key, value) ->
System.out.println(key + " : " + value));
Here is the link to the GitHub repository where you can find the entire code.