After installation java with dmg package, you can use it directly. If you need switch the java version in same host, you should set the JAVA_HOME for current user. In this blog, we explain how to set JAVA_HOME in MacOS big Sur.
Find Java Home Folder.
To set JAVA_HOME environment, we need find where the java is installed firstly. we can use the ‘java_home’ command to find it.
Open Terminal, then exec the following command:
1 | /usr/libexec/java_home -V |
After execution, the terminal display the list of java you installed and the default java version in your environment. Like this:
1 | Matching Java Virtual Machines (2): |
You can see, in our environment, we have installed two JDK versions. one is the 11 version, another is 1.8 version(Java 8).
You can use the parameter: ‘-v’ to only display the specify java home. For example, to display the java home of the 8 version, you can use the following command:
1 | /usr/libexec/java_home -v 1.8 |
Terminal display:
1 | /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home |
Detect Shell
After found the java home folder, you need detect what shell you used.
Execute the following command to show the shell information in your environment.
1 | echo $SHELL |
In our environemt, the following information shown in the terminal:
1 | /bin/zsh |
If you use bash, the informatio shoud be:
1 | /bin/bash |
Set JAVA_HOME
zsh
You should edit the ‘~/.zshenv’ or ‘~/.zshrc’ file, add the following line in the file.
1 | export JAVA_HOME=$(/usr/libexec/java_home -v 1.8) |
This command set the java 8 as the default java environment
bash
You should edit the ‘~/.bash_profile’ or ‘~/.bashrc’ file, add the following line in the file.
1 | export JAVA_HOME=`/usr/libexec/java_home -v 1.8` |
This command set the java 8 as the default java environment
Switch Java Environment
To switch java environment, you only need edit the above ‘export’ command.
For example, from java 1.8 to java 11. you change the ‘export’ command as the following:
1 | export JAVA_HOME=$(/usr/libexec/java_home -v 11) |