How to switch Java versions in Linux(using aliases)

suppose you have downloaded different JDKs in your local machine, and you have to switch among them, time to time because different applications use different JDK versions, there can be applications that are running on JDK 1.8 some of them are runs on 1.7, some newly created applications run on JDK 15.

So let’s see how we can switch among these JDK versions using aliases.

suppose you have downloaded and installed JDK 1.8 and 11(these versions can be varied in my case I have installed JDK 1.8 and JDK 11) and I have added JDK 1.8 as the default one, so when I enter

:~$ java -version

it will prompt me this message

java version "1.8.0_202"
Java(TM) SE Runtime Environment (build 1.8.0_202-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.202-b08, mixed mode)

Okay then, suppose that I want to use the installed JDK 11 version, so how i switch to JDK 11?. Let’s see how to do this.

first, open a new terminal, and then

:~$ touch .bash_java_11

this will create a .bash_java_11 file, let’s open it in vim editor(you can use any editor vim is my preferred one)

:~$ vim .bash_java_11

this will open the blank .bash_java_11 file, so in there,

# for java 11
export JAVA_HOME="/YOUR-PATH-TO-JDK/jdk-11.0.10"
export PATH=:$JAVA_HOME/bin:$PATH`java -version`

just enter the above commands, set the JAVA_HOME path according to your installed location. then save it.

now again open a new terminal and open your .bashrc file using

:~$ vim .bashrc

after opening the .bashrc enter the below line at the bottom.

alias java11='source /PATH-TO-BASH-JAVA-11-FILE/.bash_java_11'

then save the .bashrc file, finally, you have to do is source the new configurations by giving this command in terminal

:~$ source ~/.bashrc

that’s it, now you can simply switch to JDK11 by giving

:~$ java11

now if we enter

:~$ java -version

it will prompt:

java version "11.0.10" 2021-01-19 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.10+8-LTS-162)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.10+8-LTS-162, mixed mode)


now you can use JDK 11, that’s how we can switch among java versions in Linux.

I hope this small article will help you if you have any doubt please leave a comment. if you enjoy the article please give a clap, okay see you guys in another article until then Happy Coding!!!

Software Engineer at hSenid Mobile