- How to set environment variables for Java using command line
- Related Tutorials:
- About the Author:
- Environment Variables
- Querying Environment Variables
- Passing Environment Variables to New Processes
- Platform Dependency Issues
- Working with Environment Variables in Java
- How to access environment variables in Java
- How to set environment variables
- UNIX, Linux, and macOS
- Available to the current session and all child processes
- Available to the current session
- Available to a specific process
- Microsoft Windows
- Using .env files
- Reading .env files
- A note about .env file security
- That’s how to work with environment variables in Java
- Related Posts
How to set environment variables for Java using command line
Well, in this article I talked about the JVM, JRE and JDK, which are the cornerstones of the Java programming language. You develop Java applications by using tools like editors, IDEs and servers. These tools need to use the Java compiler ( javac ) and Java launcher ( java ) to compile and run Java applications, but these tools don’t know where the JRE or JDK is.
So, by setting up the environment variables, you tell your tools that:
“Hey, you can find the compiler and launcher here and there”.
The first thing you need to do after installing the JDK is creating an environment variable named JAVA_HOME and then update the PATH variable.
- JAVA_HOME : stores location of the JDK’s installation directory. When you install development tools, they will first check for the JAVA_HOME variable. If found, they will stick with it. If not, they may ask you to manually specify the location where JRE/JDK is installed.
- PATH : stores paths of directories where the operating system will look, to launch the requested programs quickly. For Java development, you should update this environment variable by adding an entry to the bin directory under JDK’s installation directory.
- JAVA_HOME = C:\Program Files\Java\jdk1.8.0
- PATH = PATH + C:\Program Files\Java\jdk1.8.0\bin
But that isn’t cool, because I’m about to show you how to do the same thing using command line prompt as shown below (Windows 7, 8 and 10):
setx JAVA_HOME "C:\Program Files\Java\jdk1.8.0" setx PATH "%PATH%;%JAVA_HOME%\bin";
The setx command permanently updates the environment variables. To add/update system environment variables, you must use the -m switch and open the command prompt using Administrator privilege: Click Start, type cmd . When the cmd.exe icon appears, right click and select Run as administrator.
To add/update system environment variables:
setx -m JAVA_HOME "C:\Program Files\Java\jdk1.8.0" setx -m PATH "%PATH%;%JAVA_HOME%\bin";
I prefer setting the environment variables using this command-line alternative. It’s quick and easy instead of going through several dialogs like using the GUI.
To summary, here are some important points:
- Always set JAVA_HOME when preparing development environment for Java.
- JAVA_HOME points to the installation directory of JDK.
- The PATH variable should contain an entry pointing to JAVA_HOME\bin .
- Environment can be set either via the GUI or command line prompt.
Related Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Environment Variables
Many operating systems use environment variables to pass configuration information to applications. Like properties in the Java platform, environment variables are key/value pairs, where both the key and the value are strings. The conventions for setting and using environment variables vary between operating systems, and also between command line interpreters. To learn how to pass environment variables to applications on your system, refer to your system documentation.
Querying Environment Variables
On the Java platform, an application uses System.getenv to retrieve environment variable values. Without an argument, getenv returns a read-only instance of java.util.Map , where the map keys are the environment variable names, and the map values are the environment variable values. This is demonstrated in the EnvMap example:
import java.util.Map; public class EnvMap < public static void main (String[] args) < Mapenv = System.getenv(); for (String envName : env.keySet()) < System.out.format("%s=%s%n", envName, env.get(envName)); >> >
With a String argument, getenv returns the value of the specified variable. If the variable is not defined, getenv returns null . The Env example uses getenv this way to query specific environment variables, specified on the command line:
Passing Environment Variables to New Processes
When a Java application uses a ProcessBuilder object to create a new process, the default set of environment variables passed to the new process is the same set provided to the application’s virtual machine process. The application can change this set using ProcessBuilder.environment .
Platform Dependency Issues
There are many subtle differences between the way environment variables are implemented on different systems. For example, Windows ignores case in environment variable names, while UNIX does not. The way environment variables are used also varies. For example, Windows provides the user name in an environment variable called USERNAME , while UNIX implementations might provide the user name in USER , LOGNAME , or both.
To maximize portability, never refer to an environment variable when the same value is available in a system property. For example, if the operating system provides a user name, it will always be available in the system property user.name .
Working with Environment Variables in Java
Environment variables are a great way to configure Java applications without having to explicitly store settings in code, such as for database and caching servers, or for third-party APIs.
Keeping such settings outside of the code has several distinct advantages:
- Avoids the need to update and recompile code when settings change
- Helps prevent exposing sensitive credentials, such as usernames and passwords, and deployment tokens
- You can deploy the same code in multiple environments
In this short article, I’m going to show you some of the ways of working with environment variables in Java.
How to access environment variables in Java
One of the most common ways is to use System.getenv(), which accepts an optional String argument. Based on whether a String argument is passed, a different value is returned from the method. Specifically:
If a String is passed and it matches a key in the internal environment Map , then its value is returned. If a matching key is not found, null is returned. If a String argument is not passed, a read-only java.util.Map containing all environment variables and their values is returned. The Map’s keys are the environment variable names and its values are the values.
Keep in mind that different platforms operate in different ways, e.g., on UNIX, Linux, and macOS, environment variables are case-sensitive, whereas on Microsoft Windows they are not.
Below, you can see an example of how to use the method to retrieve the Linux SHELL environment variable (which contains the user’s shell).
package com.settermjd.twilio.envvars; public class Main < public static void main(String[] args) < System.out.println( String.format("The current shell is: %s.", System.getenv("SHELL")) ); >>
If you want to supply a default value, call System.genenv() as follows:
How to set environment variables
As well as reading environment variables, it’s helpful to know how to set them. I won’t go into too much detail, instead sticking to the essentials. However, if you’d like to learn about them in greater depth, Dominik Kundel has written a detailed blog post about them.
UNIX, Linux, and macOS
On UNIX, Linux, and macOS, environment variables can be set in three core ways.
Available to the current session and all child processes
You can initialise environment variables so that they’re available to the current session, both the current one and any started in the current session, as well as any processes started in the current session, by using the builtin export command, as in the example below.
Setting an environment variable this way isn’t permanent. If you want to permanently set an environment variable, you need to set it in either the system-wide startup file, /etc/profile, or one of the user-specific startup files, i.e., ~/.bash_profile, ~/.bash_login, and ~/.profile.
Available to the current session
You can initialise an environment variable so that it’s available to the current session but not any child processes, as in the example below, by not using the export command.
Available to a specific process
Finally, you can initialise an environment variable so that it’s available only to a specific process. This is helpful when only that process needs the variable. You initialise it as in the example below, when starting the desired process.
USER_ID=1 retrieveUserDetails
Microsoft Windows
Setting environment variables is a little different in Microsoft Windows. You can either set them via the Control Panel, or you can set them in the command prompt or PowerShell console. There are examples of the latter two below.
# Set USER_ID in the Windows Command Prompt set USER_ID=1 # Set USER_ID in the Windows PowerShell console $Env:USER_ID = 1
Using .env files
While setting environment variables this way can be very effective, it can also become cumbersome rather quickly. For example, by setting them in the operating system’s shell, there is no concrete list of the variables which the application needs, nor is there information available about what a variable is for or what data type it must be.
Given that, among other reasons, The 12-Factor App recommended a strict separation of config from code. This practice quickly took hold throughout the developer community commonly through the use of .env (dotenv) files. These are plain text files that store a list of key/value pairs, defining the environment variables required for an application to work, as in the example below.
USER_ID=1 TWILIO_AUTH_TOKEN=1234567890987654321
To simplify getting started on a project, a further common practice emerged, that of including a .env.example file in a project which contains all of the keys—but without their values. When a new developer started working on the application, they would copy the file, naming it .env and set values for each key applicable to their local development environment.
Reading .env files
Assuming that the example above was the .env file for our project, we could use a package such as dotenv-java to make the variables available to our application.
If you’re developing in Kotlin, you can use dotenv-kotlin.
You can see an example of using the package in the code example below.
package com.settermjd.twilio.envvars; import io.github.cdimascio.dotenv.Dotenv; import io.github.cdimascio.dotenv.DotenvException; public class Main < public static void main(String[] args) < Dotenv dotenv = null; dotenv = Dotenv.configure().load(); System.out.println(String.format( "Hello World. Shell is: %s. Name is: %s", System.getenv("SHELL"), dotenv.get("NAME") )); >>
The code initialises a new Dotenv object, dotenv, and calls Dotenv.configure().load() to read in the environment variables in .env, located in the project’s root directory. Following that, dotenv.get() is used to retrieve the value of the String object passed to it. If a matching key is not found, the method returns null .
You can supply a default value as the second argument to the method if desired.
A note about .env file security
It’s important to bear in mind that if sensitive data is stored in .env, that it must not be stored under version control. If that happens, then all of the security benefits of using dotenv files is lost. That’s why it’s common to exclude them from version control, such as by adding .env (and variations of the filename) to a project’s .gitignore file when using Git.
That’s how to work with environment variables in Java
I hope this article helped you understand how to use environment variables in your Java projects.
Do you have any other ways to work with environment variables? I’d love to know!
Matthew Setter is a PHP Editor in the Twilio Voices team and a polyglot developer. He’s also the author of Mezzio Essentials and Docker Essentials. When he’s not writing PHP code, he’s editing great PHP articles here at Twilio. You can find him at msetter@twilio.com; he’s also settermjd on Twitter and GitHub.
- Matthew Setter
- Matthew Gilliard
Related Posts
Learn how to create a social task completion app with an Earth Day theme using Twilio SMS and Java Spring Boot.
A coding tutorial using Java to call the OpenAI and Twilio APIs to suggest recipes from a list of ingredients, over SMS.
Learn how to use the AWS S3 SDK in a Spring Boot project to upload and download files from an Amazon S3 bucket.
The article shows how to create Data-Driven unit tests in Spring Boot applications using the Spock Framework for Groovy and Java.
Let’s find out how to build an API to notify different users via SMS with Twilio in a Spring Boot application developed with Kotlin.
How to build an Amazon price tracker for WhatsApp using Twilio and Java Spring Boot.
- About
- Legal
- Copyright © 2023 Twilio Inc.
- All Rights Reserved.
- Protected by reCAPTCHA – Privacy – Terms