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.
Given the environment variable name, fetch the value of the variable in Java
.
We use the getEnv()
static method of the System
class in Java
to fetch the value of the specified environment variable.
public static String getenv(String name)
String name
: environment variable name.
The method returns the value for the given name. Otherwise, it returns null.
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"));}}