How to set JAVA_HOME Environment Variable in Ubuntu

Some applications require you to set the JAVA_HOME environment variable to your JDK installation directory. So in this tutorial I will explain how to find the path to the Java installation directory and set JAVA_HOME in Ubuntu Linux.

First of all we need to identify the path to the JAVA_HOME environment variable. It should be the full path to the Java installation folder where the bin directory is located.

Following command should output the correct path to JAVA_HOME (Not always).

type -p javac|xargs readlink -f|xargs dirname|xargs dirname

For example, If you Install Openjdk 8, path is something similar to the following.

/usr/lib/jvm/java-8-openjdk-amd64

For OpenJDK 9 the path is:

/usr/lib/jvm/java-9-openjdk-amd64

If you Install Oracle JDK, The path is the location where you stored the development kit.

For example, If you stored java development kit on /opt directory, The full path to the JAVA_HOME should be something similar to the following:

/opt/jdk-9.0.1

Set JAVA_HOME Variable

To set JAVA_HOME environment variable on Ubuntu, open the /etc/bash.bashrc file and add the following line:

export JAVA_HOME=/opt/jdk-9.0.1

(The value should be the path to the Java folder)

Then, use the source command to reload the /etc/bash.bashrc file:

source /etc/bash.bashrc

To check the variable, run the echo command:

echo $JAVA_HOME

Add JAVA_HOME to the PATH variable

The bin directory contains the Java executable, including javac, java, and jar. We need to add the bin directory to the PATH variable To access Java executable from anywhere within the command line.

Again, Open the /etc/bash.bashrc and add the bin directory to the PATH variable as shown below:

export JAVA_HOME=/opt/jdk-9.0.1
export PATH=$PATH:$JAVA_HOME/bin

To check the PATH variable, source the environment file and run the echo command:

source /etc/bash.bashrc
echo $PATH
set JAVA_HOME Environment Variable in Ubuntu