View RSS Feed

My Java Tips

Environment Variables

Rate this Entry
by , 11-06-2011 at 06:31 PM (1012 Views)
Environment variables are used by operating systems to pass useful information (configurations) to the applications. Environment variables are key/value pairs very much like properties. The key and the value, both are strings. To set environment variables, please read system documentation as it varies from one operating system to another.

In our Java applications, we use System.getEnv to retrieve environment variable values. If no argument is passed, getEnv will return an instance of java.util.Map which will be read only. In the returned map, the keys are the environment variable names, and the map values are the environment variable values.

Review the example below:

Java Code:
import java.util.Map;

public class EnvironmentMapEx{
    public static void main (String[] args) {
        Map environment = System.getenv();
        for (String environmentName: environment .keySet()) {
            System.out.format("%s=%s%n", environmentName, environment.get(environmentName));
A brief overview of how to retrieve environment variables is presented in first part of this post. Do read that one first.

An interesting example is presented below. We are only printing the non null environment variables.

Java Code:
        for (String env: args) {
            String value = System.getenv(env);
            if (value != null) {
                System.out.format("%s=%s%n", env, value);
            } else {
                System.out.format("%s is not assigned.%n", env);

You may want to pass environment variables to other process. This is possible. A ProcessBuilder object can be used to create a new process. In this way, the default set of environment variables is passed to the new process and this set is same as provided to the application's virtual machine process. The application can change this set using ProcessBuilder.environment.

Submit "Environment Variables" to Facebook Submit "Environment Variables" to Digg Submit "Environment Variables" to Submit "Environment Variables" to StumbleUpon Submit "Environment Variables" to Google

Tags: None Add / Edit Tags
Java SE