JAVA_HOME is an environment variable used by various Java-based applications to locate JVM (JDK) on any system. Similarly, Maven also required the JAVA_HOME to be set correctly on your system.
When I tried to check the Maven version on our macOS PC, I got the following error in the output.
mvn --versionThe JAVA_HOME environment variable is not defined correctly, this environment variable is needed to run this program.
As the error message clearly shows that the JAVA_HOME environment variable is not set on my PC. So the simple solution is to set it correctly. Use the below steps to resolve this issue.
The macOS 10.5 (Catalina) and later version use the Zsh as the default shell. The older version uses the Bash shell. So first is to identify the shell that is running on your system. Open a terminal and type:
For Zsh the output will be /bin/zsh and for the Bash shell the output will be /bin/bash.
Now, set the JAVA_HOME environment variable based on the active shell:
- Zsh (/bin/zsh): Edit the
~/.zshenvfile and append the below code.~/.zshenvexport JAVA_HOME=$(/usr/libexec/java_home)
- Bash (/bin/bash): Edit the
~/.bash_profilefile and append the below code.~/.bash_profileexport JAVA_HOME=$(/usr/libexec/java_home)
This should resolve the issue on your system. To confirm, open a new shell and print the JAVA_HOME environment variable value and also confirm with the command you were getting the error.
Note: If the issue is still not resolved after setting the environment variable correctly, make sure other scripts are not overriding it. You can find the script order of execution here.