How to set JAVA_HOME in MacOS Big Sur

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
2
3
4
Matching Java Virtual Machines (2):
11.0.11 (arm64) "Azul Systems, Inc." - "Zulu 11.48.21" /Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home
1.8.0_302 (arm64) "Azul Systems, Inc." - "Zulu 8.56.0.23" /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home

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)

本文标题:How to set JAVA_HOME in MacOS Big Sur

文章作者:Morning Star

发布时间:2021年08月21日 - 12:08

最后更新:2021年08月21日 - 15:08

原始链接:https://www.mls-tech.info/java/java-how-to-set-java-home-in-macos-big-sur/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。