Open In App

Environment Variables in Java

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Environment variables are widely used by operating systems to deliver configuration data to applications. Environment variables are key/value pairs with both the key and the value being strings, similar to properties in the Java platform.

What are Environment Variables in Java?

In Java, Environment variables are values that are stored outside of your program but can be accessed by Java code. Typically, environment variables are used to configure various features of your program or to store sensitive information like as API keys or database connection strings.

Environment variables are named values that the Java Virtual Machine (JVM) and Java applications use to configure their behavior. Any Java application that requires them can access them. They are normally specified by the operating system or the user.

How to Access Environment Variables in Java

In Java, there are two ways to access the environment variable:

  • Using System.getEnv()
  • Using System.getProperty()

1. System.getEnv()

The getEnv() function provides access to all environment variables within a Java program, however it may generate platform dependency if the program is dependent on a specific environment variable. System.getEnv() is an overloaded method in the Java API that, when invoked without an argument, provides an unmodifiable String map containing all environment variables and their values.

Syntax:

Map<String, String> envVariables = System.getenv();

Below is the implementation of the above method:

Java




// Java program to get the value
// of all environment variables at once
// using System.getenv() method
import java.util.Map;
  
// Driver Class
public class GFG {
    // main function
    public static void main(String[] args)
    {
        // Get the value of all environment variables
        // at once and store it in Map
        Map<String, String> env = System.getenv();
  
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n", envName,
                              env.get(envName));
        }
    }
}


Output

PATH=/usr/local/openjdk-11/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=eb6d4870571b
JAVA_HOME=/usr/local/openjdk-11
JAVA_VERSION=11.0.16
PWD=/home/guest/sandbox
LANG=C.UT...

2. System.getProperty()

System properties provide a more robust and platform-independent way of getting environment variables in Java programs, such as java.classpath for retrieving Java classpath or java.username for retrieving User Id which is used to run Java programs etc.

Syntax:

String sys_pro = System.getProperty(“Property_Data”);

Below is the implementation of the above method:

Java




// Java Program illustrating the working
// of getProperty(String key) method
import java.lang.*;
import java.util.Properties;
  
// Driver Class
public class NewClass {
    // main function
    public static void main(String[] args)
    {
        // Printing Name of the system property
        System.out.println(
            "user.dir: " + System.getProperty("user.dir"));
  
        // Fetches the property set with 'home' key
        System.out.println("home: "
                           + System.getProperty("home"));
        // Resulting in Null as no property is present
  
        // Printing 'name of Operating System'
        System.out.println("os.name: "
                           + System.getProperty("os.name"));
  
        // Printing 'JAVA Runtime version'
        System.out.println(
            "version: "
            + System.getProperty("java.runtime.version"));
  
        // Printing 'name' property
        System.out.println("name: "
                           + System.getProperty("name"));
        // Resulting in Null as no property is present
    }
}


Output

user.dir: /home/guest/sandbox
home: null
os.name: Linux
version: 11.0.16+8
name: null

Passing Environment Variables to New Processes

The ProcessBuilder class in Java can be used to pass environment variables to new processes. You can construct and start a new process with the ProcessBuilder class, and you can define the environment variables that you wish to provide to the process with the environment() method.

The environment() method returns a list of variables in the environment. The put() method can be used to add new environment variables to the map or to replace existing environment variables.

After you’ve added the environment variables you wish to provide to the new process, you may invoke it with the start() method.

Below is the implementation is mentioned below:

Java




// Java Program to demonstrate Passing 
// Environment Variables to New Processes
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Process;
import java.lang.ProcessBuilder;
  
// Driver Class
public class ProcessBuilderExample {
    // main function
    public static void main(String[] args) throws IOException {
        // Create a ProcessBuilder object.
        ProcessBuilder processBuilder = new ProcessBuilder("echo", "Hello, world!");
  
        // Start the process.
        Process process = processBuilder.start();
  
        // Get the output stream of the process.
        InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  
        // Read the output of the process and print it to the console.
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
  
        // Close the buffered reader.
        bufferedReader.close();
  
        // Wait for the process to finish.
        process.waitFor();
    }
}


Output:

Hello, world!

Things To Remember

  • Use system properties if the value of an environment variable is available via a system property, such as the “user.name” system property. If you access it directly through an environment variable, you may need to ask for various variables because they may be different in Windows, such as USERNAME, and Unix, such as USER.
  • Because environment variables in Unix are case sensitive and case insensitive on Windows, relying on them can make your Java program platform dependent.
  • System.In JDK 1.3, getEnv() was deprecated in favor of utilizing System.getProperty() was removed from JDK 1.5, however it was reintroduced.

Frequenty Asked Question

1. What are environment variables in programming?

Environment variables are a mechanism to store information that programs or scripts can access. They can be used to store information such as routes to specific directories, database connection details, and other sensitive data. Environment variables are typically accessed via a specific API or library in most programming languages. They are frequently used to configure an application’s or script’s behavior, such as letting the user to specify a different data directory or database server.

2. What are examples of environmental variables?

Environment variables in Windows systems are %path%, %programfiles%, %tmp%, and %systemroot%, among many others.

3. Why do we need environment variables in Java?

Setting some environment variables makes some things easier



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads