Setting the JAVA_HOME environment variable for all users in Linux typically requires system-level configuration to ensure that all current and new user sessions can access the JAVA_HOME variable. The following is a clear step-by-step solution:
-
Installing Java
First, ensure that Java is installed. You can install Java using the command line; for example, on Ubuntu, use the following command:
bashsudo apt update sudo apt install openjdk-11-jdk -
Locating the Java Installation Path
After installing Java, find the Java installation path. This can be done by running the following command:
bashupdate-alternatives --config javaThis command lists all installed Java versions and their paths. Select the version you want to set as
JAVA_HOME. -
Setting JAVA_HOME
Once you know the Java installation path, set
JAVA_HOMEfor all users. In Linux, configure this variable in the/etc/environmentfile to affect all users. To do this, edit the file with superuser privileges using a text editor, as follows:bashsudo nano /etc/environmentIn the opened file, add the following line (replace
<JAVA_PATH>with the actual Java path from the previous step and ensure you do not includebin/java):plaintextJAVA_HOME="<JAVA_PATH>"For example, if your Java path is
/usr/lib/jvm/java-11-openjdk-amd64, add:plaintextJAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"Save and close the file.
-
Making the Variable Effective
To apply the changes, ask users to log out and log back in, or run the following command to make the
/etc/environmentchanges effective immediately:bashsource /etc/environmentAlternatively, for the current session, manually export the variable:
bashexport JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64" -
Verifying JAVA_HOME Setup
To verify that
JAVA_HOMEis correctly set, run the following command in any user's session:bashecho $JAVA_HOMEIf set correctly, it should output the Java path you previously configured.
By following these steps, the JAVA_HOME environment variable will be added to the system's global environment, so all users will have this variable set in their sessions. This is very useful when installing software that requires a Java runtime environment, such as Apache Tomcat or Maven.