It generally happens that there are multiple java versions installed on a Mac system but we want a specific version out of those to be set as default.
This is required so that if an application requiring java is executed, it will pick up the desired version to avoid any compatibility issues.
In this article, we will look at the steps to be taken on Mac OS to set a particular java version to be set as default by setting JAVA_HOME environment variable.
Follow below steps to make a particular java version as default or to switch among multiple java version on your Mac system.
1. Open terminal window on Mac OS.
2. Type following command and press enter(or return).
/usr/libexec/java_home -V
You should see below output
Matching Java Virtual Machines (2):
15.0.1, x86_64: “OpenJDK 15.0.1” /Library/Java/JavaVirtualMachines/jdk-15.0.1.jdk/Contents/Home
11.0.2, x86_64: “OpenJDK 11.0.2” /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home
This shows that the system has two java versions(first column) installed.
If you can not see the desired version here, then download it and install first.
Refer this guide to install openjdk from a tar file on Mac OS.
3. Now check the current default java version by using command java -version
.
This will print
openjdk version “11.0.2” 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
Current java version being used in 11.0.2. Suppose, we want to change it to 15.0.1.
4. Type following command and press return
export JAVA_HOME=`/usr/libexec/java_home -v 15.0.1`
This will set JAVA_HOME variable to version 15.0.1.
java -version
and press return. Below is the output
openjdk version “15.0.1” 2020-10-20
OpenJDK Runtime Environment (build 15.0.1+9-18)
OpenJDK 64-Bit Server VM (build 15.0.1+9-18, mixed mode, sharing)
Note that this will only change the default java for the current terminal session.
If you close the terminal and open a new one, you will still see the older java version as the default.
6. To make it permanent default, set JAVA_HOME in .bash_profile
file.
In the terminal type,
open ~/.bash_profile
This will open a file and you should see an entry for JAVA_HOME in this file as below
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home
If you do not see any such entry, then add one.
Change the desired version of jdk as the per the output of command in Step 2 above.
Save the file. Default version of java is now updated.
You can check it by opening a new terminal window and verifying the output of java -version
.