mtnr

A tech blog with fries on the side

Install Java using Homebrew and jEnv on MacOS

Sometimes it’s desirable to use different Java versions. Here’s one way how to do it on a Mac.

Prerequisites

If you haven’t already, install Homebrew as a first step.

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

Now, that Homebrew is installed, install jEnv, next. It’ll enable you to manage multiple Java installations and to switch easily amongst them.

$ brew install jenv

Follow the steps listed in the official jEnv documentation if you’re using a shell other than zsh to configure jEnv.

You’ll find the steps necessary to configure zsh below.

$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.zshrc
$ echo 'eval "$(jenv init -)"' >> ~/.zshrc

Install JDKs

Now, that all pieces are in place, let’s install a JDK. You may chose whichever version you need. There is a list of available JDKs under https://formulae.brew.sh/formula/openjdk.

$ brew install openjdk@17

Manage JDKs

In order to manage the newly installed JDK with jEnv, let’s make jEnv aware of it.

$ jenv add /opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home/

You can chose to install additional JDKs now but we’ll check the available versions with jEnv, first.

$ jenv versions
* system (set by ~/.jenv/version)
  17
  17.0
  17.0.13
  openjdk64-17.0.13

You can easily switch between versions using the following command.

$ jenv global openjdk64-17.0.13

This will enable the selected JDK on a global level. You may also chose to only enable it in a given directory by using the local instead of global command.

You must restart you terminal for the changes to take effect.

Happy coding!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *