getEnvironmentVariable()
methodgetEnvironmentVariable()
is a 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.
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;
public static String getEnvironmentVariable(String name, String defaultValue)
String name
: The environment variable name.String defaultValue
: The default value.This method returns the environment variable value. If there is no environment variable value, it returns the default value.
import org.apache.commons.lang3.SystemUtils;public class Main{public static void main(String[] args){// Example 1String 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 2envVarName = "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();}}
environment variable name = HOME
default value = "Variable not there"
The method returns /Users/educative
, as the environment variable HOME
is available.
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.
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