Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
getenv()
communitycreator

How to list all environment variables in Java

abhilash

What is an environment variable?

Environment variable is a dynamic value that the OSOperating System and other applications may use to identify information particular to your machine.

The environment variables are in a key-value pair where the key indicates the variable’s name.

Problem statement

Write a Java program to list all the environment variables with names and values.

Solution

We use the getenv() static method of the System class in Java to retrieve all the environment variables.

Syntax

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.

Code

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));
        }
    }
}

RELATED TAGS

java
getenv()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring