Setting JAVA_HOME on Mac OS

JAVA_HOME environment variable is used to specify the location of the Java installation that is being used by your system.
In this article, you will learn different methods for setting the JAVA_HOME environment variable, including temporary and permanent settings using the terminal, .bash_profile, and /etc/environment.

1. Set JAVA_HOME temporarily
If you are working on a terminal window and want to set JAVA_HOME property for that terminal session only, then below command will be useful.

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

where export is a command, which is used to set the values of environment variables.
In the above command, the export command is used to set the value of JAVA_HOME to the output of the /usr/libexec/java_home utility.
As soon as the terminal window is closed or you try to access JAVA_HOME outside it, you will get nothing or any global/permanent value which is already set.
2. Set JAVA_HOME permanently with bash profile
To set JAVA_HOME permanently, same command is used but you need to write it in bash profile so that Mac OS reads it at start up.
First, open the bash profile with below command

nano ~/.bash_profile

Next, add this line to bash_profile

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

Save this file and then use source command to reload the environment variables as

source ~/.bash_profile

3. Set JAVA_HOME permanently with etc/environment
Another way to set JAVA_HOME variable permanently is by using /etc/environment file.
Open this file by executing below command in the terminal

sudo nano /etc/environment

and paste below line into it

JAVA_HOME=$(/usr/libexec/java_home)

Save the file and exit the editor. You may need to log out and log back in for the changes to take effect.
Meaning of /user/libexec
We have seen that we are setting JAVA_HOME environment variable as the output of /user/libexec.
But, do you know what is /user/libexec ?

/usr/libexec/ is a directory in the Mac OS file system that contains executable files which are used to support system-level services.
The java_home utility is one such executable file in this directory and is used to determine the location of the current Java installation on the system, and it returns the path to that installation.

In the below statement,

JAVA_HOME=$(/usr/libexec/java_home)

$(/usr/libexec/java_home) expression determines the location of the current Java installation and sets JAVA_HOME environment variable to it.
This allows the value of JAVA_HOME to be updated automatically, if you change the installed java version on your system, without the need to update the environment variable.

Hope the article was useful.