In an Operating System (OS) JAVA_HOME environment variable must be set to point to the directory containing the JVM. In this tutorial, we will help you to correctly set the JAVA_HOME environment variable on macOS.

Check Pre-Installed Java Versions

You can find details of all installed Java versions on macOS with the following command.

Set JAVA_HOME on macOS 10.15 and newer

The macOS Catalina (version 10.15) and the newer macOS versions usee the Zsh as the default shell. Zsh executes ~/.zshrc script during a new session starts. You can add your code in this file to the JAVA_HOME environment variable. Once the user is logged or opens a new shell the variable will automatically be set by the script. Use one of the below commands to set JAVA_HOME as per the required Java version:

Use default Java version:echo export “JAVA_HOME=$(/usr/libexec/java_home)” » ~/.zshrc Set the specific Java version by specifying it as:echo export “JAVA_HOME=$(/usr/libexec/java_home -v 1.8)” » ~/.zshrc To use a different Java version, simply replace 1.8 with the version you required like 11, 15, 17, or 18.

Set JAVA_HOME on macOS 10.14 Mojave and older

The macOS Mojave (version 10.14) and the previous macOS versions uses the Bash as the default shell. Bash runs ~/.bash_profile script everytime it started. You can easily set the JAVA_HOME environment variable using this file.

Set the default Java version:echo export “JAVA_HOME=$(/usr/libexec/java_home)” » ~/.bash_profile Set the specific Java version:echo export “JAVA_HOME=$(/usr/libexec/java_home -v 1.8)” » ~/.bash_profile To use a different Java version, simply replace 1.8 with the version you required like 11, 15, 17, or 18.

Conclusion

The JAVA_HOME is an environment variable that points to the file system location where the JDK or JRE is installed. Many Java application uses this variable to find the location of Java installed on the system.