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.
The following 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 ~/.bashrc (or /etc/profile) depending on you installed JDK or JRE, and it will set JAVA_HOME permanently.
Note that "readlink -f" command is used to get the canonical path since java or javac can be set up with multiple symlinks.
For example, if you installed Oracle JRE 7, the first export command will automatically set JAVA_HOME to:
If you installed Open JDK version 8, the second export command will set JAVA_HOME to:
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 JAVA_HOME manually.
Subscribe to Ask Xmodulo
Do you want to receive Linux related questions & answers published at Ask Xmodulo? Enter your email address below, and we will deliver our Linux Q&A straight to your email box, for free. Delivery powered by Google Feedburner.
Did you find this tutorial helpful? Then please be generous and support Xmodulo!