How to Set JAVA_HOME on macOS
In this tutorial, I am going to share with you how to set the JAVA_HOME environment variable on a new macOS. The new way of setting JAVA_HOME environment variable allows us to dynamically identify and use the current Java version installed on a computer as well as let us switch between Java versions if there is more than one installed.
Starting from macOS 10.5 there is a very convenient command that we can use to identify the installed Java version. For example, open the terminal window on your Mac and type the following command to print out the top Java version installed on your Mac
If you have more than one version installed and you want to see all of the versions available, then run the following command in the terminal window.
To print the current Java version installed, simply use
Set JAVA_HOME Environment Variable
- Open the terminal windows and type:
This will open the .profile file for editing.
export JAVA_HOME=$(/usr/libexec/java_home)
Switch Between Java Versions
If you have more than one Java version installed on your computer and you need to switch to using a different version, you can do so by adding the -v flag.
Let’s have a look at a short example.
To learn what Java versions I have installed on my Mac computer I will type the following in the terminal window:
Matching Java Virtual Machines (2): 13.0.1, x86_64: "Java SE 13.0.1" /Library/Java/JavaVirtualMachines/jdk-13.0.1.jdk/Contents/Home 1.8.0_231, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home /Library/Java/JavaVirtualMachines/jdk-13.0.1.jdk/Contents/Home
Which tells that there are two Java versions installed and the top version is “jdk-13.0.1.jdk“.
- In the terminal window type
To open the .profile file for editing.
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
or if I wanted to set Java version 13, I would do it this way
export JAVA_HOME=$(/usr/libexec/java_home -v 13)
Now if you check Java version by typing
It should print the current Java version set in JAVA_HOME.
I hope this tutorial was helpful to you.