After spending hours reading half baked or old medium articles explaining how to setup java in macOS, I made an updated version that covers what I think are the best tricks.
# remove any versions. autocomplete should help
brew uninstall adoptopenjdk8
brew untap AdoptOpenJDK/openjdk
# same as before: remove the respective versions
brew uninstall openjdk8
AdoptOpenJDK is moving to Eclipse so installing the Eclipse Temurin is the way to go.
# Install Java 17.
# replace 8 with 11, 15, etc for different versions
brew tap homebrew/cask-versions
brew install --cask temurin8
A long time ago, rbenv provided a solid and easy way to manage several versions of ruby. After this, good spin offs were made like pyenv and some terrible like nvm.
In Java case, jenv seems to be the best one, mirroring rbenv commands and style.
brew install jenv
Doing eval "$(jenv init -)"
will seriously slowdown your terminal (a common
problem for this types of problems). But there is a easy way around this which
is to lazy load jenv.
This script is available for zsh. It might be simple to replicate in bash, but since most macOS's nowadays use zsh anyway, i will focus on it.
Simply close and use
# Clone to custom plugins
git clone https://github.com/shihyuho/zsh-jenv-lazy .oh-my-zsh/custom/plugins/jenv-lazy
Add the plugin to your plugin list in .zshrc
# .zshrc
plugins=(... pyenv-lazy jenv-lazy)
Clone this to any folder (I will clone it to .config/zsh/plugins)
git clone https://github.com/shihyuho/zsh-jenv-lazy ~/.config/zsh/plugins/jenv-lazy
source it in the .zshrc
#.zshrc
source ~/.config/zsh/plugins/jenv-lazy/jenv-lazy.plugin.zsh
Like explained in the jenv website, add the java versions installed into jenv.
# depending on the version, replace the 17
jenv add /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home/
It might be good to use one of this versions by default. So just do this:
jenv global 17.0.3