You can have multiple versions of Java on your Mac.
In this article we show how to install Java on Mac using Homebrew, and how to allow to switch between different versions such as Java8, Java11, Java13 and latest Java version.
Pre-requisites
Before we start, make sure you have Homebrew installed on your Mac. If not, you can install it via:
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Next, install Homebrew Cask
$ brew tap homebrew/cask-versions
$ brew update
$ brew tap caskroom/cask
Install Latest Version of Java Using Brew
To install the latest version of Java, all you need to do is:
$ brew cask install java
Install Specific Versions of Java (Java8, Java11, Java13)
To install previous or specific versions of JDKs, you can get them from AdoptOpenJDK:
$ brew tap adoptopenjdk/openjdk
$ brew cask install adoptopenjdk8
$ brew cask install adoptopenjdk11
$ brew cask install adoptopenjdk13
Switch Between Different Versions of Java
If you want to switch between different versions of Java, you need to add the following to your .bash_profile
.
In this case, we want to be able to switch between Java8 and Java11:
export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)
alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'
# default to Java 11
java11
Reload .bash_profile
for the aliases to take effect:
$ source ~/.bash_profile
Then, you can use the aliases to switch between different Java versions:
$ java8
$ java -version
java version "1.8.0_261"
Conclusion
In this post we learned how to install any version of Java on Mac using Homebrew.