Installing Java and setting JAVA_HOME / PATH variables on Linux

Java is a programming language and computing platform first released by Sun Microsystems. Later on Sun Microsystems was acquired by Oracle. When it comes to Installing Java and setting JAVA_HOME / PATH variables on Linux distributions, there are more than one options –

Using official package manager for the Linux distribution that you are using (eg apt-get for Ubuntu)

This article is based on “Ubuntu 14.04.4 LTS” Linux OS distribution, and we will use the option 1 above to demonstrate how to Installing Java and setting JAVA_HOME / PATH variables.

Installing Java and setting JAVA_HOME / PATH variables

Check Whether Java is already installed:

Before continuing make sure you don’t have installed Java. Open terminal and invoke following command. If you do not have Java then you will see blank line. That will mean you DON’T have Java installed. By default Java is located in /usr/lib/jvm/java-<version>, directory

whereis javajava:

Installing Java

Now to install java, just download Java from the path – JAVA 8 Link. Once Downloaded, you will get the file like jdk-8u102-linux-x64.tar.gz. Unzip the file to a directory and copy the folder to /opt directory of your machine. I prefer to copy it to opt directory, so that it is accessible to all the users of the system.

Set $JAVA_HOME and $PATH variables:

How can I set JAVA_HOME and PATH variables for every user under my Linux system?

Well, ~/.bash_profile is a startup script which generally runs once. This particular file is used for commands which run when the normal user logs in. Common uses for .bash_profile are to set environment variables such as PATH, JAVA_HOME, to create aliases for shell commands, and to set the default permissions for newly created files.

Setting JAVA_HOME / PATH for a single user

Login to your account and open .bash_profile file.

vim ~/.bash_profile

Set JAVA_HOME using syntax export JAVA_HOME=<path-to-java>. If your path is set to /opt/jdk180102/bin/java, set this as follows. Also set the PATH as follows.

Feel free to replace /opt/jdk180102/bin/java as per your setup. Save and close the file. Just logout and login back to see new changes. Alternatively, type the following command to activate the new path settings immediately:

# source ~/.bash_profile

OR

# . ~/.bash_profile

Verify new settings:

# echo $JAVA_HOME# echo $PATH# which java

Please note that the file ~/.bashrc is similar, with the exception that ~/.bash_profile runs only for Bash login shells and .bashrc runs for every new Bash shell.

Set JAVA_HOME / PATH for all users

You need to setup global config in /etc/profile OR /etc/bash.bashrc file for all users: