Skip to content

Instantly share code, notes, and snippets.

@ijash
Last active November 10, 2019 17:25
Show Gist options
  • Save ijash/a52a1018ef56f265b7a59378348d6c44 to your computer and use it in GitHub Desktop.
Save ijash/a52a1018ef56f265b7a59378348d6c44 to your computer and use it in GitHub Desktop.

Installing Java on ubuntu

Installing multiple version of java

  1. Check java version:

    java --version

    if exist, it may be version 11 and above.

  2. install another version of java (in this case java 8 openjdk):

    	sudo apt install openjdk-8-jdk openjdk-8-jre
  3. To change the default version, use the update-alternatives tool as shown below:

    sudo update-alternatives --config java

    (OPTIONAL)Some applications written in Java are using the JAVA_HOME environment variable to determine the Java installation location.

    To set the JAVA_HOME environment variable, enter this command:

    cat >> /etc/environment <<EOL
    JAVA_HOME= /usr/lib/jvm/java-8-openjdk-amd64
    JRE_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre
    EOL

Use Script to Switch Java Version

If you frequently switch between different Java versions, it is a good idea to write a short script to automate the process. Here is the script I used for switching to OpenJDK 8 on my machine.

put this on java8.sh file

sudo update-java-alternatives -s java-1.8.0-openjdk-amd64
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64/
export PATH=$PATH:$JAVA_HOME

Similarly, you can create scripts for other Java versions installed on your machine. The next step is to add these scripts as aliases to .bashrc file.

...
# Java Alias
alias java8='source /opt/java/switch/java8.sh'
alias java11='source /opt/java/switch/java11.sh'

Next, run the following command to load the changes of .bashrc file:

$ source ~/.bashrc

Now if you want to switch to Java 8, just type the following command in your terminal:

$ java8

one of the source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment