How to get the value of an environment variable in Java

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"));
}
}
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources