Home »
Java programming language
Java System class getenv() method with example
System class getenv() method: Here, we are going to learn about the getenv() method of System class with its syntax and example.
Submitted by Preeti Jain, on September 12, 2019
System class getenv() method
- getenv() method is available in java.lang package.
- getenv() method is used to return an unmodifiable Map of the current environment variable in key-value pairs.
- We will see what is environment variable ? An environment variable is a system dependent external named value.
- We should go for environment variable when a system interface needed an environment variable (such as PATH).
- When we assign the value of the environment variable then we don’t need to assign the value of the environment variable again while working.
- getenv() method is a static method so it is accessible with the class name too.
- getenv() method method may throw an exception at the time of retrieving the environment variable:
SecurityException: If a particular method checkPermission() does not allow access to the process environment when the security manager exists.
Syntax:
public static Map getenv ();
Parameter(s):
- This method does not accept any parameter.
Return value:
The return type of this method is Map, it returns the environment variable with the desired value.
Example:
// Java program to demonstrate the example of
// getenv() method of System Class.
import java.util.*;
import java.lang.*;
public class GetenvMethod {
public static void main(String[] args) {
Map < String, String > map = System.getenv();
// By using keyset() method is used to iterate
Set < String > system_keys = map.keySet();
for (String keys: system_keys) {
System.out.println("system_key= " + keys);
String values = map.get(keys);
System.out.println("system_key_value= " + values);
}
}
}
Output
E:\Programs>javac GetenvMethod.java
E:\Programs>java GetenvMethod
system_key= PATH
system_key_value= /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-10-jdk/bin
system_key= SHELL
system_key_value= /bin/bash
system_key= HOSTNAME
system_key_value= jdoodle
system_key= JAVA_OPTS
system_key_value= --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED
system_key= PWD
system_key_value= /home
system_key= SHLVL
system_key_value= 1
system_key= HOME
system_key_value= /root
system_key= _
system_key_value= /usr/bin/time