How to set JAVA_HOME environment variable on macOS?

in .bash_profile:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.xx/Contents/Home

Adding the below answer to help those who are looking for step by step instructions on how to setup Java_Home on a Mac.

  1. Determine whether Java is installed by using the command below:

    which java
    

You will something like this - /usr/bin/java

  1. Next Step will be to determine the version of Java Installed by using the command below:

    java -version
    

You will see something like java version "1.8.0_131"

  1. Next step will be to get the location where the Java is installed:

    cd /Library/Java
    
  2. Under the Java folder, select the folder with the version that was displayed earlier:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
    
  3. Next check if Java_Home is setup to the correct location:

    echo $JAVA_HOME
    

It will result in blank output if it is not already setup. If it returns the location, check if it points to the correct folder.

  1. You can add or update the Java_Home using the below commands:

    vi ~/.bash_profile
    

Navigate to the end of the file by pressing "Shift + g". Now press "i" to get to insert mode. Add the below lines in the bash_profile after replacing the path to the java home directory on your mac

    # Setting Java_Home
    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

Save this by pressing Esc followed by ":wq!"

  1. Finally open a new terminal window and test the variable is setup correctly:

    echo $JAVA_HOME
    

It should return the Java_Home path setup