This tutorial will help you to set the JAVA_HOME environment variable on the latest older macOS operating systems. The /usr/libexec/java_home is the command line utility that returns the Path of the Java home directory from the current user’s settings. You can use this utility to set up the JAVA_HOME environment variable on your macOS.

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.

/usr/libexec/java_home -V 

Ouput:

Matching Java Virtual Machines (5): 18.0.1, x86_64: "OpenJDK 18.0.1" /Library/Java/JavaVirtualMachines/temurin-18.jdk/Contents/Home 16.0.1, x86_64: "AdoptOpenJDK 16" /Library/Java/JavaVirtualMachines/adoptopenjdk-16.jdk/Contents/Home 15.0.1, x86_64: "AdoptOpenJDK 15" /Library/Java/JavaVirtualMachines/adoptopenjdk-15.jdk/Contents/Home 11.0.9.1, x86_64: "AdoptOpenJDK 11" /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home 1.8.0_275, x86_64: "AdoptOpenJDK 8" /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home /Library/Java/JavaVirtualMachines/temurin-18.jdk/Contents/Home

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 ~/.bashrc 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)" >> ~/.bashrc
    
  • Set the specific Java version:
    echo export "JAVA_HOME=$(/usr/libexec/java_home -v 1.8)" >> ~/.bashrc
    

    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.