What are Environment Variables?
Every computer programming language contains variables and constants which allocate unique memory locations, containing information to be used by the programs. Constant values are not changeable but the variable’s value can be changed. Environment variables are the key/value pair whose value is set outside the program and their reference is always available to the program at any time. Both key and value are strings. The conventions for setting and using environment variables always differ between operating systems and command line interpreters. They are always globally available to every application running on the system.Example
PATH = "C:\\WINDOWS\system32;"
Here, Path is the environment variable set outside the program but available to each program running on windows.
Use Case
As we know every change in the program needs to be executed or re-deployed to the server which may produce unwanted side effects in production. So the main purpose of introducing environment variables is to restrict this execution and deployment again and again.How To Get Environment Variables in Java?
Let’s see how to get environment variables in java. Java provides us with 2 ways to get environment variables in the Java program.System.getenv()
System.getProperty()
System.getenv()
The System.getenv() method is used to fetch all the environment variables but if a specific key name is provided as a parameter then it will fetch its value. java.lang.System.getenv() always returns the string map of all the available environment variables.Declaration
public static String getenv(String name)
Here, name is the parameter used to specify the key against which we needed the value.
Return
It will return the value of the key or null if the provided parameter is not associated with any key. If the parameter is not passed then it will return all the available key/value pairs.Example
import java.util.Map;
public class SystemGetEnvDemo {
public static void main(String[] args) {
// getting value for environment variable "PATH"
System.out.print("System.getenv(PATH) = ");
System.out.println(System.getenv("PATH"));
// getting value for environment variable "TEMP" resulting in null
System.out.print("System.getenv(TEMP) = ");
System.out.println(System.getenv("TEMP"));
//getting all environment variables using System.getenv()
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}
Output
System.getProperty()
We can also use java.lang.System.getProperty() in Java to retrieve the value for the specified key passed as a parameter to this method. This method is used to retrieve the system properties, i.e information about the local system and configurations. If the environment variable is present as a system property in java then it’s better to use System.getProperty() for getting value in a platform-independent way. The value for properties can be changed at the runtime but not the case with environment variables.Declaration
public String getProperty(String name)
Here, name is the parameter used to specify the key against which we needed the value.
Return
It will return the value of the key or null.Example
import java.lang.*;
import java.util.Properties;
public class SystemGetPropertyDemo {
public static void main(String[] args)
{
// getting username system property
// using System.getProperty in Java
System.out.println("user.name: " + System.getProperty("user.name"));
// getting property with key home resulting in null
// calling system.getproperty()
System.out.println("home: " + System.getProperty("home"));
// getting name of Operating System
System.out.println("os.name: " + System.getProperty("os.name"));
}
}
Output
Using ProcessBuilder
to Pass Environment Variables to New Processes
Java’s ProcessBuilder
class allows developers to create and manage operating system processes. One of its key features is the ability to pass environment variables to the processes it starts. This capability is essential for controlling the execution context of external processes launched from Java applications.
Example: Passing Environment Variables to a New Process
import java.io.IOException;
public class PassEnvironmentVariables {
public static void main(String[] args) {
try {
// Create a ProcessBuilder
ProcessBuilder processBuilder = new ProcessBuilder("env");
// Access and modify the environment variables
processBuilder.environment().put("MY_VAR", "HelloWorld");
// Start the new process
Process process = processBuilder.start();
// Print the output of the process
process.getInputStream().transferTo(System.out);
} catch (IOException e) {
System.err.println("Error starting process: " + e.getMessage());
}
}
}
In this example, the ProcessBuilder
sets the MY_VAR
environment variable before starting the process. The process inherits this variable, which can then be accessed by the new environment.
Modifying Environment Variables Using ProcessBuilder.environment()
The environment()
method of ProcessBuilder
returns a modifiable map of the process’s environment variables. This allows developers to add, modify, or remove variables as needed for the new process.
Example: Modifying Environment Variables
import java.io.IOException;
public class ModifyEnvironmentVariables {
public static void main(String[] args) {
try {
// Create a ProcessBuilder for a shell command
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "echo $MY_VAR");
// Modify the environment variables
processBuilder.environment().put("MY_VAR", "ModifiedValue");
// Start the new process
Process process = processBuilder.start();
// Print the output of the process
process.getInputStream().transferTo(System.out);
} catch (IOException e) {
System.err.println("Error starting process: " + e.getMessage());
}
}
}
This example demonstrates how to modify an existing variable or create a new one. The shell command echo $MY_VAR
outputs the modified value of MY_VAR
.
Implications of Setting Environment Variables for New Processes
Setting environment variables for new processes provides several benefits and implications that developers should consider:
Isolation of Execution Context
By setting environment variables specifically for a new process, developers can isolate the execution context of that process. This is particularly useful in scenarios where different processes require different configurations or credentials.
Improved Debugging
Environment variables set via ProcessBuilder
can help in debugging by providing a controlled environment for testing specific scenarios without affecting the global environment.
Security Considerations
Passing sensitive information through environment variables can pose security risks. Use secure mechanisms, such as encrypted values or temporary variables, to mitigate these risks when handling sensitive data.
Example: Configuring an Application-Specific Environment
import java.io.IOException;
public class ApplicationEnvironmentSetup {
public static void main(String[] args) {
try {
// Create a ProcessBuilder for a mock application
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
// Set environment variables specific to the application
processBuilder.environment().put("APP_ENV", "Production");
processBuilder.environment().put("API_KEY", "12345-secure-key");
// Start the process
Process process = processBuilder.start();
// Print the output
process.getErrorStream().transferTo(System.out); // For commands like java -version
} catch (IOException e) {
System.err.println("Error starting process: " + e.getMessage());
}
}
}
GO TO FULL VERSION