[Solved]: Error: JAVA_HOME is not defined correctly, when installing Maven on Mac

Problem Statement: 

I have added JAVA_HOME to .bash_profile file like this:

$ vi .bash_profileexport JAVA_HOME=/usr/libexec/java_home$ source .bash_profile

But, when executing the Maven command, it prompts following error messages :

$ mvn -versionError: JAVA_HOME is not defined correctly.  We cannot execute /usr/libexec/java_home/bin/java


All steps to set JAVA_HOME correctly: 

Step 1: Open Terminal (Command+R, type Terminal, Hit ENTER).Step 2: Add the following line to ~/.bash_profile.export JAVA_HOME=$(/usr/libexec/java_home)Step 3:  Now run the following command.  source ~/.bash_profile

Update the JAVA_HOME like following :

1). Open .bash_profile 

$ vi .bash_profile

2. Add JAVA_HOME to .bash_profile

If you .bash_profile is something like this

export M2_HOME=/Users/admin/apache-maven-3.5.0export PATH=$PATH:$M2_HOME/bin

Then add following lines

export JAVA_HOME=$(/usr/libexec/java_home)export PATH=$PATH:$JAVA_HOME

Final .bash_profile

export M2_HOME=/Users/admin/apache-maven-3.5.0export PATH=$PATH:$M2_HOME/binexport JAVA_HOME=$(/usr/libexec/java_home)export PATH=$PATH:$JAVA_HOME

3. source .bash_profile

Don’t forget to source .bash_profile

$ source .bash_profile

Run Maven again :

username$ mvn -versionApache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T01:09:06+05:30)Maven home: /Users/admin/Downloads/apache-maven-3.5.0Java version: 9.0.1, vendor: Oracle CorporationJava home: /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/HomeDefault locale: en_IN, platform encoding: UTF-8OS name: "mac os x", version: "10.13.3", arch: "x86_64", family: "mac"username$

Checking JAVA_HOME:

You can check the exact value of JAVA_HOME by typing the following command.


The value(output) returned will be something like below.


That’s it.

Note: Apple recommends setting JAVA_HOME to “/usr/libexec/java_home“,