Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
getenv()
communitycreator

How to get the value of an environment variable in Java

abhilash

What is an environment variable?

A dynamic value that the operating system and other applications may use to identify information particular to your machine is known as an environment variable.

Environment variables are in the form of key-value pairs, where the key indicates the variable’s name.

Problem overview

Given the environment variable name, fetch the value of the variable in Java.

Solution

We use the getEnv() static method of the System class in Java to fetch the value of the specified environment variable.

Syntax

public static String getenv(String name)

Parameters

String name: environment variable name.

Return value

The method returns the value for the given name. Otherwise, it returns null.

Code

In the code below, we fetch the values for two environment variables, PATH and JAVA_HOME.

public class Main {

    public static void main(String[] args) {
        System.out.println("PATH for Java: " + System.getenv("PATH"));
        System.out.println("Java Home: " + System.getenv("JAVA_HOME"));
    }
}

RELATED TAGS

java
getenv()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring