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 Gradle
, Ant
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 7, Fedora, RHEL/ 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-1.8.0.201.b09-2.el7_6.x86_64/jre/bin/java)
+ 2 java-11-openjdk.x86_64 (/usr/lib/jvm/java-11-openjdk-11.0.19.0.7-1.el7_9.x86_64/bin/java)
Enter to keep the current selection[+], or type selection number: 2
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
/usr/lib/jvm/java-11-openjdk-11.0.19.0.7-1.el7_9.x86_64
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/java.sh
Then confirm:
echo $JAVA_HOME
echo $PATH
echo $CLASSPATH
And that’s all. You application should locate the Java installation directory.
Recommended books:
Also check: