Last updated on September 22, 2020 by Dan Nanni
JAVA_HOMEenvironment variable to point to the installed JDK. What is the recommended way to set
JAVA_HOMEenvironment variable on Linux?
Many Java programs or Java-based IDE environments require
JAVA_HOME environment variable being set. This environment variable is supposed to point to the top directory where the Java development kit (JDK) or Java runtime environment (JRE) is installed. The JDK contains everything the JRE offers, but also provides additional binaries and libraries needed to compile Java programs (e.g., compilers, debugger, JavaDoc). While the JDK is needed to build Java applications, the JRE alone is sufficient to simply run already built Java programs.
When you are trying to set
JAVA_HOME environment variable, the complication is that
JAVA_HOME variable will change depending on (1) whether you installed JDK or JRE, (2) which version of JDK/JRE you installed, and (3) whether you installed Oracle JDK or Open JDK.
So whenever your build or run-time environment changes (e.g., upgrade to a newer JDK), you need to adjust
JAVA_HOME accordingly, which is cumbersome.
export commands will allow you to set
JAVA_HOME environment variable automatically regardless of these factors.
If you installed JRE:
export JAVA_HOME=$(dirname $(dirname $(readlink -f $(which java))))
If you installed JDK:
export JAVA_HOME=$(dirname $(dirname $(readlink -f $(which javac))))
Place either of the above commands in
/etc/profile) depending on you installed JDK or JRE, and it will set
readlink -f command is used to get the canonical path since
javac can be set up with multiple symlinks.
For example, if you installed Oracle JRE 7, the first
export command will automatically set
If you installed Open JDK version 8, the second
export command will set
In short, these
export commands will automatically update
JAVA_HOME variable as you re-install/upgrade your JDK/JRE packages or change default Java version. No need to adjust
Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.