Set JAVA_HOME on CentOS / RHEL / Fedora

Posted on 222 views

I’ve seen many questions on how to set JAVA_HOME on CentOS / Fedora / RHEL Linux distributions. JAVA_HOME is used to set the path of Java installation on a Linux or Windows system. JAVA_HOME is just a convention and it is usually used by Java EE and Tomcat servers and build tools such as GradleAnt and Maven to find where Java is installed.

In this guide I’ll show you an easy and recommended way of setting JAVA_HOME on CentOS / Fedora / RHEL Linux system. We assume you already have Java installed before you can set JAVA_HOME.

Install Java on CentOS 7FedoraRHEL/ CentOS 8.

Set JAVA_HOME on CentOS / Fedora / RHEL

If you have more than one version of Java installed, you may want to set default version before you configure JAVA_HOME on CentOS / Fedora / RHEL system. For this, use the command below.

sudo alternatives --config java

This will give you a prompt to confirm the default Java version you want to set.

There are 2 programs which provide 'java'.

  Selection    Command
*  1           java-1.8.0-openjdk.x86_64 (/usr/lib/jvm/java-1.8.0-openjdk-
 + 2           java-1.7.0-openjdk.x86_64 (/usr/lib/jvm/java-1.7.0-openjdk-

Enter to keep the current selection[+], or type selection number: 1

You can set JAVA_HOME in .bash_profile, .bashrc file or for all Global users in /etc/profile or as bash function inside /etc/profile.d/ directory.

Add below line to any of bash dotfiles mentioned above.

export JAVA_HOME=$(dirname $(dirname $(readlink $(readlink $(which javac)))))

Then source the file. Suppose you added this to ~/.bashrc, you’ll run:

source ~/.bashrc

Confirm Environment variable value.

$ echo $JAVA_HOME

You also need to add Java /bin directory to your PATH

export PATH=$PATH:$JAVA_HOME/bin

Java CLASSPATH can be set using:

export CLASSPATH=.:$JAVA_HOME/jre/lib:$JAVA_HOME/lib:$JAVA_HOME/lib/tools.jar

So your complete setting will have the lines:

export JAVA_HOME=$(dirname $(dirname $(readlink $(readlink $(which javac)))))
export PATH=$PATH:$JAVA_HOME/bin
export CLASSPATH=.:$JAVA_HOME/jre/lib:$JAVA_HOME/lib:$JAVA_HOME/lib/tools.jar

Here is my screenshot.


Don’t forget to source the file or logout and back in.

# Examples
source ~/.bashrc
source ~/.bash_profile
source /etc/profile
source /etc/profile.d/

Then confirm:

echo $PATH

And that’s all. You application should locate the Java installation directory.

Gravatar Image
A systems engineer with excellent skills in systems administration, cloud computing, systems deployment, virtualization, containers, and a certified ethical hacker.