Setting up JAVA_HOME environment variable is the very first thing, which every programmer should know how to do in order to get started with Java development, as many Java-based applications, tools and libraries depend on JAVA_HOME.

In this article, I’d like to share with you guys, about how to setup JAVA_HOME environment variable on macOS / Linux operating system, with both Bash shell and Z-shell.

Basically, you can use the following commands in a terminal for setting JAVA_HOME and updating PATH environment variables:

export JAVA_HOME=$HOME/jdk-version/Contents/Home

export PATH=$JAVA_HOME/bin:$PATH

However, these commands have effect only in the current session. If you exit the terminal and open a new one, you will the changes lost.

So how to permanently set JAVA_HOME and update PATH environment variables on macOS / Linux? Read on to know how. And I suppose that you already have JDK (Java Development Kit) installed.

 

1. Set JAVA_HOME permanently in Z-shell

Z-shell (zsh) is the default shell in latest macOS operating systems. Firstly, you need to create a Z-shell resource file (.zshrc) in your user home directory, using the following command in terminal:

cat > .zshrc

Then type the following commands as content of the file:

export JAVA_HOME=$HOME/jdk-17.0.1.jdk/Contents/Home

export PATH=$JAVA_HOME/bin:$PATH

Note that the HOME environment variable refers to your user home directory. And I suppose that you have JDK installed in jdk-17.0.1.jdk directory, which is in your home directory.



Press Ctrl + D to save the file. The .zhsrc file is executed at shell’s startup, so every time you open a new terminal with Z-shell, the JAVA_HOME environment variable is set and PATH environment variable is updated.

Now you can type java -version or javac -version to verify. You should see the output looking something like this:

set java home on macos zsh

Now, quit the terminal. Then open a new one. Type java -version command again and you should see the change is permanent.

 


2. Set JAVA_HOME permanently in Bash shell

To setup JAVA_HOME with Bash shell, you create the Bash profile file (.bash_profile instead of .zshrc) in your user home directory, like this:

cat > .bash_profile

export JAVA_HOME=$HOME/jdk-17.0.1.jdk/Contents/Home

export PATH=$JAVA_HOME/bin:$PATH

set java home on macos bash

Press Ctrl + D to save the file. The .bash_profile file is executed at shell’s startup, so every time you open a new terminal with Bash shell, the JAVA_HOME environment variable is set and PATH environment variable is updated.

That’s how to set JAVA_HOME environment variable on macOS, with both Bash shell and Z-shell. It is also working on Linux.

 

Related Articles:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment