Java System.getenv() – Examples
In this tutorial, we will learn about the Java System.getenv() function, and learn how to use this function to get all environment variables or value for a specific environment variable, with the help of examples.
getenv()
System.getenv() returns an unmodifiable string map view of the current system environment.
Syntax
The syntax of getenv() function is
getenv()
Returns
The function returns Map<String,String> object.
Example 1 – getenv()
In this example, we will get the Map view of System Environment and print all these mappings.
Java Program
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s = %s%n", envName, env.get(envName));
}
}
}
Output
USERDOMAIN_ROAMINGPROFILE = DESKTOP-QRVE3I1
PROCESSOR_LEVEL = 6
SESSIONNAME = Console
ALLUSERSPROFILE = C:\ProgramData
PROCESSOR_ARCHITECTURE = AMD64
PSModulePath = C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
SystemDrive = C:
USERNAME = TutorialKart
ProgramFiles(x86) = C:\Program Files (x86)
FPS_BROWSER_USER_PROFILE_STRING = Default
PATHEXT = .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
COMPOSE_CONVERT_WINDOWS_PATHS = true
DriverData = C:\Windows\System32\Drivers\DriverData
IntelliJ IDEA Community Edition = C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.1\bin;
ProgramData = C:\ProgramData
Based on the environment variables set in your PC, the output may change.
getenv(String name)
System.getenv(name) gets the value of the specified environment variable name.
System.getenv(), without any argument passed to it, returns a map of all the environment variables. But, if you pass a specific key to this getenv() method, it returns the value corresponding to that environment variable.
Syntax
The syntax of getenv(name) function is
getenv(String name)
where
Parameter | Description |
---|---|
name | The name of environment variable. |
Returns
The function returns String object.
Example 2 – getenv(String name)
In this example, we will get the specific environment variables like TEMP, OS, JAVA_HOME, USERNAME, PROCESSOR_ARCHITECTURE, etc., using System.getenv(name) method.
Java Program
public class Example {
public static void main(String[] args) {
System.out.println(System.getenv("TEMP"));
System.out.println(System.getenv("OS"));
System.out.println(System.getenv("JAVA_HOME"));
System.out.println(System.getenv("USERNAME"));
System.out.println(System.getenv("PROCESSOR_ARCHITECTURE"));
}
}
Output
C:\Users\TutorialKart\AppData\Local\Temp
Windows_NT
C:\Program Files\Java\jdk1.8.0_201
TutorialKart
AMD64
Conclusion
In this Java Tutorial, we have learnt the syntax of Java System.getenv() function, and also learnt how to use this function with the help of examples.