Techscrypt

Manage multiple Java versions on MacOS

javasetup

Install Jenv

Jenv can be installed from the instructions on their website.


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

Install Plugins

Install the maven plugin to ensure that maven uses correct version of Java


jenv enable-plugin maven

Ensure that JAVA_HOME is correct


jenv enable-plugin export

Verify Install

Run doctor to verify the installation


jenv doctor

This should print something similar to

[OK]	JAVA_HOME variable probably set by jenv PROMPT
[OK]	Java binaries in path are jenv shims
[OK]	Jenv is correctly loaded

Install Java

We will install AdoptOpenJDK, since all AdoptOpenJDK binaries and scripts are open source licensed and available for free.

You can read more about the differences here

Install Java on macOS using brew


brew install AdoptOpenJDK/openjdk/adoptopenjdk8

Or install multiple versions with


brew install AdoptOpenJDK/openjdk/adoptopenjdk{11,16}

Add Java versions to Env

List all java versions using


/usr/libexec/java_home -V

This will show all the versions installed on the machine - something similar to this

Matching Java Virtual Machines (4):
16.0.1 (x86_64) "AdoptOpenJDK" - "AdoptOpenJDK 16" /Library/Java/JavaVirtualMachines/adoptopenjdk-16.jdk/Contents/Home
14.0.2 (x86_64) "AdoptOpenJDK" - "AdoptOpenJDK 14" /Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home
11.0.10 (x86_64) "AdoptOpenJDK" - "AdoptOpenJDK 11" /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
1.8.0_282 (x86_64) "AdoptOpenJDK" - "AdoptOpenJDK 8" /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home

You could list a particular version as well


# for example, to find the location of java 11

/usr/libexec/java_home -v11

# this would print

/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home

Add the preferred versions to jenv


jenv add <path_to_java_version>

# To add version 11 to jenv

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

Similarly, all installed versions can be added to jenv. Once they are added, we can check java versions added to jenv


jenv versions

This will show all the versions added to jenv and indicate the active version


  system
* 1.8 (set by /Users/sidswork/.jenv/version)
  1.8.0.282
  11
  11.0
  11.0.10
  16
  16.0
  16.0.1
  openjdk64-1.8.0.282
  openjdk64-11.0.10
  openjdk64-16.0.1

Configure

Configure the global (default) java version


jenv global <version>

# ex: to set the version to 11.0
jenv global 11.0

Configure the shell instance java version


jenv shell <version>

# ex: to set the version to 11.0
jenv shell 11.0

References

  1. AdoptOpenJDK
  2. JENV
  3. Oracle JDK vs OpenJDK
  4. AdoptOpenJDK installation