Environment variable is a dynamic value that the
The environment variables are in a key-value pair where the key indicates the variable’s name.
Write a Java program to list all the environment variables with names and values.
We use the getenv()
static method of the System
class in Java to retrieve all the environment variables.
public static java.util.Map<String, String> getenv()
The method takes no parameters. It returns a Map where the map keys are the environment variable name, and map values are the environment variable value.
In the code below, we get all the environment in the form of Map
.
Next, we loop through the Map
to get individual environment variable names and values.
import java.util.Map;public class Main {public static void main(String[] args) {Map<String, String> envMap = System.getenv();for (String envName : envMap.keySet()) {System.out.format("%s = %s%n", envName, envMap.get(envName));}}}