Environment Variables in Java
Last Updated :
24 Oct, 2023
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));
}
}
}
OutputPATH=/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
}
}
Outputuser.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
Similar Reads
Setting up Environment Variables For Java
In the journey to learning the Java programming language, setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Now, this guide on how to setting up environment variables for Java is a one-place solution for Mac, Win
5 min read
How To Set Environment Variables In Jenkins ?
Jenkins is a widely used open-source automation server that facilitates continuous integration and continuous delivery (CI/CD) processes. One powerful feature of Jenkins is its capability to configure environment variables, which are important for various functions like defining parameters, paths, a
6 min read
Rule Engines in Java
Rule engines in Java provide us with a framework for managing and performing business rules in a flexible and defining manner. These engines allow the developers to separate the business logic from the application code by making it easier to modify and understand rules without changing the core appl
9 min read
Java Variables
In Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated. Key Components of Variables in Java: A variable in Java has three components, which are listed below: Data Type: Defines the k
9 min read
Static Variables in Java
In Java, when a variable is declared with the static keyword. Then, a single variable is created and shared among all the objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable. These are the main scenarios when we u
3 min read
Rules For Variable Declaration in Java
Variable in Java is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data. A variable is a name given to a memory location. For More
2 min read
Scope of Variables in Java
The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about
7 min read
User-Defined Packages in Java
Packages in Java are a mechanism to encapsulate a group of classes, interfaces, and sub-packages. In Java, it is used for making search/locating and usage of classes, interfaces, enumerations, and annotations easier. It can be considered data encapsulation also. In other words, we can say a package
3 min read
Are Static Local Variables Allowed in Java?
In Java, there are different types of variables, each with its own behavior and scope. Understanding these variables plays a very important role. In this article, we will discuss the concept of static with local variables, and we will also discuss in Java static local variables are allowed or not. W
3 min read
Spring - Variable in SpEL
EvaluationContext interface is implemented by the StandardEvaluationContext class. To resolve properties or methods, it employs a reflection technique. The method setVariable on the StandardEvaluationContext can be used to set a variable. Using the notation #variableName, we may utilize this variabl
3 min read