Installing and Using Multiple Java(JDK) Versions on Mac OS

How to set the desired version as the default when multiple Java(JDK) versions are installed on macOS

This article explains how to set the desired version as the default when multiple Java(JDK) versions are installed on macOS.

Check the Current Default Java Version

First, check the Java version currently installed and used by default.

% java -version
openjdk version "17.0.4.1" 2022-08-12 LTS
OpenJDK Runtime Environment Corretto-17.0.4.9.1 (build 17.0.4.1+9-LTS)
OpenJDK 64-Bit Server VM Corretto-17.0.4.9.1 (build 17.0.4.1+9-LTS, mixed mode, sharing)

In the example above, you can see that openjdk 17 is being used.

Check Installed Java Versions

Next, check the installed Java versions.

% /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    17.0.4 (arm64) "Amazon.com Inc." - "Amazon Corretto 17" /Users/user/Library/Java/JavaVirtualMachines/corretto-17.0.4.1/Contents/Home
    11.0.16.1 (arm64) "Azul Systems, Inc." - "Zulu 11.58.23" /Users/user/Library/Java/JavaVirtualMachines/azul-11.0.16.1/Contents/Home
/Users/user/Library/Java/JavaVirtualMachines/corretto-17.0.4.1/Contents/Home

The output above shows that Java 17 and 11 are installed.

Change the JAVA_HOME Path

Change the JAVA_HOME path as follows.

% export JAVA_HOME=$(/usr/libexec/java_home -v 11)
% source ~/.zshrc

In the example above, the JAVA_HOME path was changed to JDK 11.

Check the Current Java Version Again

Check the currently installed and used Java version again to see whether the change was applied correctly.

% java -version
openjdk version "11.0.16.1" 2022-07-19 LTS
OpenJDK Runtime Environment Zulu11.58+23-CA (build 11.0.16.1+1-LTS)
OpenJDK 64-Bit Server VM Zulu11.58+23-CA (build 11.0.16.1+1-LTS, mixed mode)

As in the example above, you can see that it has changed to openjdk 11.

Configure with an Environment Variable

After applying the setting above, if you close and reopen the command shell, it will probably return to the original JDK version.

Change the Environment Variable in a Settings File

One way to apply the change every time is to put the environment variable in the settings file(~/.zshrc) as follows.

export JAVA_HOME=$(/usr/libexec/java_home -v 11)

Delete JDKs You Will Not Use

Alternatively, delete the JDKs you will not use as follows.

% cd /Users/cjos/Library/Java/JavaVirtualMachines/
% sudo rm -rf corretto-17.0.4.1