What is SystemUtils.getEnvironmentVariable() in Java?
The getEnvironmentVariable() method
getEnvironmentVariable() 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.
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-langpackage, 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 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();}}
Example 1
environment variable name = HOMEdefault value = "Variable not there"
The method returns /Users/educative, as the environment variable HOME is available.
Example 2
environment variable name = random-env-namedefault 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
- undefined by undefined