In this blog post, you will learn to install different-2 Java versions on macOS using Homebrew.

Pre-Requisites

Before starting the installation of Java using this tutorial you must have the following prerequisites

Terminal: You must have Mac Terminal access and little knowledge about working with the terminal application. Ao login to your Mac system and open terminal Homebrew: This tutorial relies on Homebrew, So you must have homebrew installed. Homebrew can be installed with a single command. You can follow these instructions to install Homebrew

How to Install Java on MacOS

The Homebrew contains the latest stable java version along with the LTS release Java 8, 11 LTS, and Java 17. Follow the below steps to install the specific version of Java or all the available Java versions on your macOS system.

Setup JAVA_HOME and Switching Version

The /usr/libexec/java_home command returns a path suitable for setting the JAVA_HOME environment variable. It determines this path from the preferred JVMs in the Java Preferences application. Use the below steps to configure JAVA_HOME environment variable. Also, know about switching to the default Java version. Here the formulae “openjdk” is always referred to as the latest Java version. Other than that, OpenJDK 8, 11, and 17 are also available. Brew installation of OpenJDK doesn’t set reference than Celler directory. For the system, Java wrappers to find this JDK, symlink it with: Use one of the below options to install the required Java version. If required, You can also install all the versions on a single system:

Install Java 8:brew install [email protected] sudo ln -sfn /usr/local/opt/[email protected]/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-1.8.jdk Install Java 11:brew install [email protected] sudo ln -sfn /usr/local/opt/[email protected]/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk Install Java 17:brew install [email protected] sudo ln -sfn /usr/local/opt/[email protected]/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-17.jdk

The installation process may take some time to complete depending on your network speed. When you want to switch the JDK versions again, update the ~/zshenv or ~/.bash_profile and update JAVA_HOME to another JDK version.

Save the file and close it. The above configuration will set the JAVA_HOME environment variable and also update the PATH as well. Uncomment the line to change different Java versions:

Conclusion

This tutorial explained you to how to install Java on macOS. Also provides you steps to switching between multiple installed Java versions.