How to work with Java on your Mac, including having multiple versions of Java on your Mac

The easiest way to install Java on your Mac is by using homebrew. Honestly, if you don’t have homebrew on your Mac, I highly recommend you do that. Plus it’s easy to do. All you need is to enter the following:


$ /bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)”

Now that you have homebrew installed, you can install Java by entering:
$ brew install java

That should install the latest version of it. If you want to install an older version, you can do something like this:
$ brew install java11

If you’ve done this a few times, you may have a few different version of Java installed liked me, and if you enter the following command it may look something like this:

% ls /usr/local/opt | grep openjdk
openjdk
openjdk@11
openjdk@18
openjdk@19
openjdk@20
openjdk@21
%

As you can see, I have a few different versions installed. However, if I do this:

% java --version
openjdk 11.0.20.1 2023-08-24
OpenJDK Runtime Environment Homebrew (build 11.0.20.1+0)
OpenJDK 64-Bit Server VM Homebrew (build 11.0.20.1+0, mixed mode)
%

It shows the OS thinks I have JDK version 11 running.

Why is that? Well, it turns out if I enter this:

% ls /Library/Java/JavaVirtualMachines/
jdk1.8.0_261.jdk openjdk-11.jdk
%

I can see I have two JDKs installed there. MacOS will go with the latest JDK there when you ask what version is installed, in this case openjdk-11.

If I want the OS to use a different version like openjdk 21, I can enter this symbolic link (all one line):

sudo ln -sfn /usr/local/opt/openjdk@21/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-21.jdk

Then when I check on things, I see the following:


% java --version
openjdk 21 2023-09-19
OpenJDK Runtime Environment Homebrew (build 21)
OpenJDK 64-Bit Server VM Homebrew (build 21, mixed mode, sharing)
% ls /Library/Java/JavaVirtualMachines/
jdk1.8.0_261.jdk openjdk-11.jdk openjdk-21.jdk
%

Now the system thinks openJDK 21 is running.

If I want to reverse this and go back to openjdk 11, I can use this unlink command and see this:

% sudo unlink /Library/Java/JavaVirtualMachines/openjdk-21.jdk
% java --version
openjdk 11.0.20.1 2023-08-24
OpenJDK Runtime Environment Homebrew (build 11.0.20.1+0)
OpenJDK 64-Bit Server VM Homebrew (build 11.0.20.1+0, mixed mode)
% ls /library/Java/JavaVirtualMachines
jdk1.8.0_261.jdk openjdk-11.jdk
berniemichalik@Bernies-MacBook-Air-4 ~ %

Normally I would recommend going with the latest and greatest version of Java on your Mac. However, you may have a situation where you have some Java code that only runs on older versions of Java. This is one way to deal with that.

For more on this, here are some good links I found:

Comments are closed.