Switching between JDK versions on MacOS

Sometimes you need to switch between JDK versions to work on different projects. Adjust bash script or JAVA_HOME will be bothering and time-consuming. jEnv was born to do the job for you. Let’s get started!

Install JDKs on your own by different ways.
For example, I have JDK 1.8 and JDK 11 on my machine.

hn-localizedirect:JavaVirtualMachines hieunguyenduc$ pwd
/Library/Java/JavaVirtualMachines
hn-localizedirect:JavaVirtualMachines hieunguyenduc$ ls -al
total 0
drwxr-xr-x  4 root  wheel  128 Jun  6 17:15 .
drwxr-xr-x  4 root  wheel  128 Jun  3 13:21 ..
drwxr-xr-x  3 root  wheel   96 Jun  6 17:15 jdk-11.0.3.jdk
drwxr-xr-x  3 root  wheel   96 Jun  3 13:21 jdk1.8.0_211.jdk

1) Install jenv using Homebrew

brew install jenv

2) Load jenv in your bash

echo 'eval "$(jenv init -)"' >> ~/.bash_profile

3) To make sure JAVA_HOME is set, enable export plugin

jenv enable-plugin export

4) Add JDKs to jenv

jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/jdk-11.0.3.jdk/Contents/Home

5) List all installed JDK versions

hn-localizedirect:Home hieunguyenduc$ jenv versions
  system
* 1.8 (set by /Users/hieunguyenduc/.jenv/version)
  1.8.0.211
  11.0
  11.0.3
  oracle64-1.8.0.211
  oracle64-11.0.3

6) Switch to your favorite JDK (globally)

JDK 1.8

hn-localizedirect:Home hieunguyenduc$ jenv global 1.8
hn-localizedirect:Home hieunguyenduc$ java -version
java version "1.8.0_211"
Java(TM) SE Runtime Environment (build 1.8.0_211-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.211-b12, mixed mode)
hn-localizedirect:Home hieunguyenduc$ echo $JAVA_HOME
/Users/hieunguyenduc/.jenv/versions/1.8

JDK 11.0

hn-localizedirect:Home hieunguyenduc$ jenv global 11.0
hn-localizedirect:Home hieunguyenduc$ java -version
java version "11.0.3" 2019-04-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.3+12-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.3+12-LTS, mixed mode)
hn-localizedirect:Home hieunguyenduc$ echo $JAVA_HOME
/Users/hieunguyenduc/.jenv/versions/11.0

That’s it!

References: http://www.jenv.be/

Leave a comment