System.getenv(): This method is available in java.lang.System class of Java.
Approach 1: When a method takes one argument.
Syntax:
String java.lang.System.getenv(String name)
This method takes one argument of type String as its parameter. This method gets the value of the specified environment variable. An environment variable is a system-dependent external named value.
Parameters: One parameter is required for this method.
name the name of the environment variable.
Returns: the string value of the variable, or null if the variable is not defined in the system environment.
Throws:
1. NullPointerException - if the name is null.
2. SecurityException - if a security manager exists and its checkPermissionmethod doesn't allow access to the environment variable name.
Approach 1.1: When no exceptions
Java
public class Systemgetenv {public static void main(String[] args) {String name = "os.name";System.out.println(System.getenv(name));}}
Output:
null
Approach 1.1: NullPointerException
Java
public class Systemgetenv {public static void main(String[] args) {String name = null;System.out.println(System.getenv(name));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "s1" is null at java.base/java.lang.ProcessEnvironment$NameComparator.compare(ProcessEnvironment.java:202) at java.base/java.lang.ProcessEnvironment$NameComparator.compare(ProcessEnvironment.java:195) at java.base/java.util.TreeMap.getEntryUsingComparator(TreeMap.java:374) at java.base/java.util.TreeMap.getEntry(TreeMap.java:344) at java.base/java.util.TreeMap.get(TreeMap.java:279) at java.base/java.lang.ProcessEnvironment.getenv(ProcessEnvironment.java:279) at java.base/java.lang.System.getenv(System.java:1019)
Approach 2: When the method takes no arguments.
Syntax:
Map<String, String> java.lang.System.getenv()
This method returns an unmodifiable string map view of the current system environment. The environment is a system-dependent mapping from names to values which is passed from parent to child processes.
Note: If the system does not support environment variables, an empty map is returned.
Returns: the environment as a map of variable names to values.
Throws:
SecurityException - if a security manager exists and its checkPermissionmethod doesn't allow access to the process environment.
Java
public class Systemgetenv2 {public static void main(String[] args) {System.out.println("Number of values is " + System.getenv().size());}}
Output:
Number of values is 43
No comments:
Post a Comment