How to Set the JAVA_HOME Variable in Linux?

In this article, we’ll learn to set the JAVA_HOME variable in Linux. JAVA_HOME should be correctly set on your system in order for you to be able to run Java programs successfully. In case there is an error, you will get the following error :

Error: JAVA_HOME is not defined correctly.
We cannot execute /usr/java/jdk1.7.0_05/bin/java

To avoid getting this error you will have to set your JAVA_HOME path. This is a step by step tutorial about how you can do that. The process is slightly different for setting it for a single user and all users. We will go over both in this tutorial.

Set the JAVA_HOME variable for a single user

Let’s start by checking if JAVA_HOME contains the correct path or not. You can display the path using :

echo $JAVA_HOME
Echo Java Home

If it contains a path, you will see the output. In case the variable is empty, you will not get an output. If the output is empty you can proceed with the steps below to set it.

1. Install Java on Linux

The first step is to make sure that you have Java installed on your system. To check the version of java installed run the following command:

java -version

2. Open .bashrc file

The .bashrc file is a bash shell configuration file. It is stored at ~/.bashrc and gets executed every time a user starts up a fresh terminal session in interactive mode on their Linux system. Environment variables are stored in this file.

To open this file use the vim editor.

vim ~/.bashrc

To edit in vim press ‘i‘.

Once you are in insert mode add the following line to the file.

export JAVA_HOME=/usr/java/jre1.8.0_04

Make sure you use the correct java version in the statement above.

Java Vi

3. Source ~/.bashrc

Run the source command as shown below to make sure that the changes are reflected.

source ~/.bashrc

4. Print JAVA_HOME

You can check if the path was correctly set by using the echo command.

echo $JAVA_HOME
Echo Javahome

Set the JAVA_HOME variable for all users

The steps to set JAVA_HOME variable for all users are similar to setting it for a single user. You will need to log in as root or execute the commands using the sudo command.

1. Open /etc/bashrc file

Changes in global configurations are done by editing the /etc/bashrc file. You can open the /etc/bashrc file using the command:

vim /etc/bashrc file

To edit in vim press ‘i‘.

Add the following line:

export JAVA_HOME=/usr/java/jre1.8.0_04

Make sure you use the correct java version.

2. Run source /etc/profile

To make sure that the changes are reflected immediately use the source command as follows:

source /etc/profile

This will successfully update the path in JAVA_HOME variable.

3. Print JAVA_HOME

To check if the path was set successfully use:

echo $JAVA_HOME

Conclusion

This tutorial covered the steps to update the JAVA_HOME variable in Linux. You can read through this tutorial to learn how to install Java in Linux. Continue to follow LinuxForDevices for more tutorials on Linux.