(Resolved) JAVA_HOME environment variable is not defined correctly on macOS

Channel: Linux
Abstract: For Zsh the output will be /bin/zsh and for the Bash shell the output will be /bin/bash. NowThe JAVA_HOME environment variable is not defined correctl

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.

The Problem:

When I tried to check the Maven version on our macOS PC, I got the following error in the output.

mvn --version 

The JAVA_HOME environment variable is not defined correctly,
this environment variable is needed to run this program.
Error: JAVA_HOME environment variable is not defined correctlyThe Solution:

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:

echo $SHELL 

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 ~/.zshenv file and append the below code.
    ~/.zshenv 
    export JAVA_HOME=$(/usr/libexec/java_home)
    
  • Bash (/bin/bash): Edit the ~/.bash_profile file and append the below code.
    ~/.bash_profile
    export 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.

echo $JAVA_HOME 
mvn --version 
Resolved: JAVA_HOME is not defined correctly

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.

Ref From: tecadmin

Related articles