Install jEnv which will allow us to manage Java versions on global and local levels

brew install jenv

Now add jEnv to system PATH by updating configuration of macOS shell:

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

Load updated terminal configuration:

source ~/.zshrc

Ensure proper integration with Maven:

jenv enable-plugin export
jenv enable-plugin maven

Install Java version(-s)

brew install java

Brew will install latest version of Java and add a symlink in /opt/homebrew/opt directory. For example, /opt/homebrew/opt/openjdk. There are other links inside of this directory which ultimately lead to the real folder where the installation is located:

/opt/homebrew/Cellar/openjdk/<javaversion>/libexec/openjdk.jdk/Contents/Home

So now we need to add all existing Java installations into jEnv by copying those paths and running the command jenv add <path>

jenv add /opt/homebrew/Cellar/openjdk/18.0.1/libexec/openjdk.jdk/Contents/Home

After that you can list available versions in jenv:

jenv versions

Here is how you can switch global and local Java versions.

Global version setup:

jenv global <version>

Directory (project) specific Java:

jenv local <version>

Java for current terminal window:

jenv shell <version>

And of course you can always check Java version in current context by

java -version