What is SystemUtils.getEnvironmentVariable() in Java?

The getEnvironmentVariable() method

getEnvironmentVariable() is a staticdescribes the methods in Java that can be called without creating an object of the class method of the SystemUtils class that is used to retrieve the value of an environment variable.

If the variable cannot be read, then the method returns the default value passed as parameter.

How to import SystemUtils

The definition of SystemUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the SystemUtils class as follows:


import org.apache.commons.lang3.SystemUtils;

Syntax


public static String getEnvironmentVariable(String name, String defaultValue)

Parameters

  • String name: The environment variable name.
  • String defaultValue: The default value.

Return value

This method returns the environment variable value. If there is no environment variable value, it returns the default value.

Code

import org.apache.commons.lang3.SystemUtils;
public class Main{
public static void main(String[] args){
// Example 1
String envVarName = "HOME";
String defaultValue = "Variable not there";
System.out.printf("The output of SystemUtils.getEnvironmentVariable for '%s' is '%s'", envVarName, SystemUtils.getEnvironmentVariable(envVarName, defaultValue));
System.out.println();
// Example 2
envVarName = "random-env-name";
defaultValue = "Variable not there";
System.out.printf("The output of SystemUtils.getEnvironmentVariable for '%s' is '%s'", envVarName, SystemUtils.getEnvironmentVariable(envVarName, defaultValue));
System.out.println();
}
}

Example 1

  • environment variable name = HOME
  • default value = "Variable not there"

The method returns /Users/educative, as the environment variable HOME is available.

Example 2

  • environment variable name = random-env-name
  • default value = "Variable not there"

The method returns the default value, i.e., Variable not there, as the environment variable is not there.

Expected output

The output of the code is as follows:


The output of SystemUtils.getEnvironmentVariable for 'HOME' is '/Users/abhi'
The output of SystemUtils.getEnvironmentVariable for 'random-env-name' is 'Variable not there'

Free Resources