This comprehensive Linux guide expects that you run the following commands as root user but if you decide to run the commands as a different user then ensure that the user has sudo access and that you precede each of the privileged commands with sudo

You can use multiple versions of java on your linux system for development and different software requirements.
In this tutorial, we will guide you about switching between different versions of java using command line in Debian/Ubuntu.

Displaying Available Versions

To display the list of available versions of the java installed on your system, you can run the following command

root@codesposts:~$ update-java-alternatives --list

java-1.11.0-openjdk-amd64      1111       /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-12-oracle                 1091       /usr/lib/jvm/java-12-oracle

Switching Java Default Version

You can switch between different versions of java installed on your system by running the following command on your system.

root@codesposts:~$ update-alternatives --config java

There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                         Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java   1111      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java   1111      manual mode
* 2            /usr/lib/jvm/java-12-oracle/bin/java          1091      manual mode

Press <enter> to keep the current choice[*], or type selection number:2 

Enter the number of the desired java version and press ENTER.

Verifying Version

You can verify the default version of Java on your system by running the following command on your system.

root@codesposts:~$ java --version

java 12.0.2 2019-07-16
Java(TM) SE Runtime Environment (build 12.0.2+10)
Java HotSpot(TM) 64-Bit Server VM (build 12.0.2+10, mixed mode, sharing)

Setting Default Version Of javac

You can follow the same steps to set the default version of javac on your system.

root@codesposts:~$ update-alternatives --config javac

There is 1 choice for the alternative javac (providing /usr/bin/javac).

  Selection    Path                                   Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-12-oracle/bin/javac   1091      auto mode
* 1            /usr/lib/jvm/java-12-oracle/bin/javac   1091      manual mode
Press <enter> to keep the current choice[*], or type selection number:

Setting Environment Variables

You can run the following commands to set the environment variables for java.

root@coddesposts:~$ export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

root@codesposts:~$ export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")