Skip to content

Instantly share code, notes, and snippets.

@mvaneggermond
Last active September 4, 2020 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvaneggermond/07962394276a2c701edc7086b4e87ad0 to your computer and use it in GitHub Desktop.
Save mvaneggermond/07962394276a2c701edc7086b4e87ad0 to your computer and use it in GitHub Desktop.
Switching Java versions on OS X

You can view the installed versions on your computer by entering the following command in terminal:

/usr/libexec/java_home -V

For instance, I have the following versions installed:

14.0.2, x86_64:	"Java SE 14.0.2"	/Library/Java/JavaVirtualMachines/jdk-14.0.2.jdk/Contents/Home
11.0.8, x86_64:	"AdoptOpenJDK 11"	/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
11.0.8, x86_64:	"Java SE 11.0.8"	/Library/Java/JavaVirtualMachines/jdk-11.0.8.jdk/Contents/Home

You can specify the Java version to use by setting the JAVA_HOME environment variable:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/

To switch Java versions easily, you can add the following lines to the file bash_profile. Note that I specify the JAVA_HOME in different ways. By using the nifty utility java_home you can get the installation directory by specificying the version or architecture. Given that I have two Java versions 11.08 installed, I specified the home directory directly for each of these versions (without the quotation marks!).

nano ~/.bash_profile

alias j14="export JAVA_HOME=`/usr/libexec/java_home -v 14`; java -version"
alias j11="export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-11.0.8.jdk/Contents/Home; java -version"
alias oj11="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home; java -version

Close the file and source it to make use of it immediately

source ~/.bash_profile

Switch between Java versions by entering one of the aliases:

j14

java version "14.0.2" 2020-07-14
Java(TM) SE Runtime Environment (build 14.0.2+12-46)
Java HotSpot(TM) 64-Bit Server VM (build 14.0.2+12-46, mixed mode, sharing)

Please pay caution on where you install Java. By installing Java with brew directly, the JAVA_HOME might be overwritten. Hence, you should install it with brew cask install or directly download Java from the vendor. You can read more here.

I started looking into the switching of Java versions as I was using rJAVA. After switching Java versions, you should relink R to Java by typing R CMD javareconf (for me without sudo privileges) and restart your R session.

I am not the first one to face this issue. An elaborate post can be found here:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment