How to switch java versions in Mac OS?

A Mac does not come with a default Java installed. If we need to do something with Java we will have to install java into the Mac OS. There are many ways to install Java in Mac OS.

We might have multiple Java versions installed in Mac and we may need to switch versions. In this article we see ways to switch between different Java versions.

First of all we can check all the available java versions installed in Mac using following command:

$ /usr/libexec/java_home -V

Matching Java Virtual Machines (2):
    11.0.2, x86_64:	"OpenJDK 11.0.2"	/Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/Contents/Home
    1.8.0_222, x86_64:	"AdoptOpenJDK 8"	/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home


In the .bash_profilefile if we simply add the following line with the desired version then it will switch to that specific version.

export JAVA_HOME=`/usr/libexec/java_home -v 1.8`

We can confirm this by checking the installed java version using the following command:

$ java --version
openjdk 11.0.2 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

A good reference about Java version switching.