1. Install Homebrew
  2. Install AdoptJDK
  3. Install jenv
    1. Add your AdoptJDK installation to jenv
    2. Set the global Java version using jenv
  4. Set up .zshrc
  5. Test it out

An ages-long problem that once in a while comes to take a couple of hours away from a developer: How to properly manage multiple versions of Java in a single Mac, and how to switch between them painlessly.

Perhaps more importantly, other applications such as Maven should be aware of the version of Java that is active and use that one. This can be achieved by dynamically setting up the JAVA_HOME environment variable.

In this guide we will configure our environment using Homebrew, AdoptJDK 1.8, jenv, and set up our zsh to automatically load the appropriate java version and set JAVA_HOME for us whenever we start up the terminal. This is what makes Maven and other tools use our default Java version until we change it using jenv.

Tested on macOS Big Sur, but should work in other versions.

Install Homebrew

Basically apt-get / rpm / yum / apk / <yet another Linux package manager that we need to learn because reasons>, but for Mac. And because Mac only has one distro, you only need to learn one package manager! /s.

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

It works. Use it.

Install AdoptJDK

1
2
brew tap AdoptOpenJDK/openjdk
brew install --cask adoptopenjdk8

Install jenv

It is like nvm for Java. Thank the Gods for this.

1
brew install jenv

Add your AdoptJDK installation to jenv

1
jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home

Set the global Java version using jenv

1
jenv global 1.8

Set up .zshrc

Now we need to edit ~/.zshrc to automatically load and change the set JAVA_HOME for us on startup.

1
vim ~/.zshrc

Add at the end of the file (Shift + g) → a → Cmd+V → Esc → :wq → Enter

1
2
3
4
5
6
7
8
9
10
# set up jenv
export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
 
# Magic lines, credits https://github.com/jenv/jenv/issues/44
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"
alias jenv_set_java_home='export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"'
 
# call function on boot to set the JAVA_HOME var on every terminal startup
jenv_set_java_home

Test it out

Open a new Terminal and run this line.

1
java -version

It should print out version 1.8, which is the one we installed.