> ## Content Index
> Fetch the complete content index at: https://www.ggorantala.dev/llms.txt
> Use this file to discover other available public pages before exploring further.

# How to Set JAVA_HOME on Windows, macOS and Linux (and Check It)
- URL: https://www.ggorantala.dev/set-java-home-windows-macos-linux/
- Published: 2026-11-29T20:29:36.000Z
- Updated: 2026-11-29T20:29:36.000Z
- Description: How to set JAVA_HOME so Maven, Gradle and your IDE all agree on one JDK: the exact path to use on Windows, macOS and Linux, why it vanishes in cron, sudo and CI, and the one command that proves it's right.
- Author: Gopi Gorantala
- Tags: java-home, environment-variables, shell-startup-files, java-home-macos, jdk-setup, java-errors, linux, windows

## One line in .bashrc, one Gradle error

This is the line that breaks most first attempts to set JAVA\_HOME. I've typed it myself, and I've approved it in other people's pull requests:

```bash
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64/bin

```

It looks reasonable. That folder is where `java` lives. And Gradle 8.14.3 answers it like this:

```log
$ gradle -v

ERROR: JAVA_HOME is set to an invalid directory: /usr/lib/jvm/java-21-openjdk-amd64/bin

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

```

Maven 3.9.11 is vaguer about the same mistake:

```log
$ mvn -v
The JAVA_HOME environment variable is not defined correctly,
this environment variable is needed to run this program.

```

Meanwhile `java -version` in the same terminal works fine, which is the part that makes people doubt the error. If you're here to set JAVA\_HOME for the first time, or to work out why tools keep complaining about it, the whole job comes down to two things: point it at the JDK's top folder (the one that *contains* `bin`), and put it somewhere that every process you care about actually reads.

Here's what I checked for this one: the exact messages from Maven 3.9.11 and Gradle 8.14.3 for each wrong value, what four different kinds of Linux shell see from the same startup file, and whether the `java` launcher reads JAVA\_HOME at all. All on OpenJDK 21.0.13.1 on Ubuntu 24.04\. The Windows and macOS steps come from Adoptium's installer docs and Apple's `java_home` man page. I didn't run those in this lab, so there's no captured output for them below.

## Who reads JAVA\_HOME, and who ignores it

The surprise first, because it explains most of the confusion. **The `java` command doesn't read JAVA\_HOME.** Set it to a folder that doesn't exist and run java anyway:

```log
$ JAVA_HOME=/nonexistent java -version
openjdk version "21.0.13.1" 2026-11-17

$ JAVA_HOME=/nonexistent java -XshowSettings:properties -version 2>&1 | grep java.home
    java.home = /usr/lib/jvm/java-21-openjdk-amd64

```

The launcher works out its own home from where its binary sits. `PATH` decides which `java` your shell runs. JAVA\_HOME is a convention that *other programs* use to find a JDK: the `mvn` and `gradlew` scripts, Tomcat's `catalina.sh`, Ant, most IDEs, plenty of CI plugins. So `java -version` working tells you nothing about JAVA\_HOME, and a correct JAVA\_HOME doesn't fix `java: command not found` (that's [a PATH problem](https://ggorantala.dev/java-command-not-found/?ref=ggorantala.dev)).

That gives you the two-minute check. Ask the JDK where it lives, then compare:

```bash
java -XshowSettings:properties -version 2>&1 | grep java.home   # where the java on PATH lives
echo "$JAVA_HOME"                                                 # what tools will use
"$JAVA_HOME/bin/javac" -version                                   # must work, or JAVA_HOME is wrong

```

The first two lines should print the same folder. If they don't, your terminal runs one JDK and your build runs another, and sooner or later that turns into an [UnsupportedClassVersionError](https://ggorantala.dev/unsupportedclassversionerror/?ref=ggorantala.dev). The third line catches a JAVA\_HOME that points at a JRE, which has no `javac`. (Same root cause as [javac not being recognized](https://ggorantala.dev/javac-is-not-recognized/?ref=ggorantala.dev).)

## Watch it go missing in four shells

Correct value is half of it. The other half is *where* you set it, and Linux makes this easy to see. Make a throwaway home folder with only a `.bashrc` in it, then start shells the four ways real programs start them. `env -i` wipes the inherited environment, so nothing leaks in from your current session.

```bash
mkdir -p /tmp/jh-lab/home
echo 'export JAVA_HOME=/opt/from-bashrc' > /tmp/jh-lab/home/.bashrc
B="env -i HOME=/tmp/jh-lab/home PATH=/usr/bin:/bin TERM=dumb"

$B bash -ic 'echo $JAVA_HOME'     # interactive terminal
$B bash -c  'echo $JAVA_HOME'     # how cron, CI steps and most scripts run
$B bash -lc 'echo $JAVA_HOME'     # login shell (ssh, su -)
$B sh -c    'echo $JAVA_HOME'     # /bin/sh, which is dash on Ubuntu

```

What I got:

```log
interactive non-login: /opt/from-bashrc
bash -c:               []
login (bash -lc):      /usr/lib/jvm/java-21-openjdk-amd64
sh -c (dash):          []

```

The empty brackets are the classic "works in my terminal, fails in Jenkins" result. A non-interactive `bash -c` doesn't read `.bashrc`, and dash doesn't read it ever.

The login-shell line threw me. I'd expected either `/opt/from-bashrc` or nothing, and got a real JDK path I hadn't set anywhere. I spent a few minutes thinking bash had sourced `.bashrc` through some Ubuntu default. It hadn't. The image I ran this in had a `/etc/profile.d/java.sh` that someone had added (no package owns it, `dpkg -S` finds nothing), and login shells run everything in `/etc/profile.d`. Add a `~/.profile` with its own export and that one wins:

```log
login with .profile:   /opt/from-profile

```

That detour is the lesson, more or less. On a machine you didn't build, JAVA\_HOME may already be set by a file you've never opened, so check `grep -rn JAVA_HOME /etc/profile /etc/profile.d /etc/environment ~/.profile ~/.bashrc ~/.zshrc 2>/dev/null` before you add another one.

Two more wrong values I tried against Maven, both producing the "not defined correctly" message above: a path in literal quotes (`JAVA_HOME='"/usr/lib/jvm/..."'`, which happens when you paste quotes into a GUI field or a `.env` file), and a variable set without `export`, which the child process never sees at all.

Teardown is `rm -rf /tmp/jh-lab`. Nothing else was touched.

## The short answer

JAVA\_HOME is a plain environment variable that build tools read to find a JDK. Set it to the JDK's root folder, the one with `bin`, `lib` and `release` inside, never to `bin` itself. Then add `$JAVA_HOME/bin` to `PATH` so the `java` in your terminal and the JDK your tools use are the same one.

## Why a variable set in one place is missing in another

Environment variables aren't global. Each process gets a copy from whoever started it, at the moment it started, and changes never flow backwards or sideways. Every "I set it and it's not there" story comes down to which parent started the process you're looking at.

On Linux, an interactive terminal reads `~/.bashrc` (or `~/.zshrc`). A login shell reads `/etc/profile`, the files in `/etc/profile.d/`, and then the first of `~/.bash_profile`, `~/.bash_login` or `~/.profile`. Cron starts jobs with a tiny environment and reads none of these. `sudo` with Ubuntu's default `env_reset` (I checked `/etc/sudoers` in the lab) throws most of your variables away. A systemd service gets only what its unit file gives it. `/etc/environment` is read by `pam_env` at login, and it isn't a shell script: the lab showed that a line like `PATH=$JAVA_HOME/bin:...` is kept as literal text, dollar sign and all, so variables don't expand there.

macOS has the same model with zsh as the default shell, plus one extra trap. Apps launched from the Dock or Finder don't start from your shell, so they never see `~/.zshrc`. That's a big enough topic to get its own article.

Windows keeps user and system variables in the registry. A Command Prompt or PowerShell window copies them when it opens. Set JAVA\_HOME while a window is open and that window still has the old value, and so does any IDE that was already running. Close them and open new ones.

## How to set JAVA\_HOME on each OS

### Linux

Find the real JDK root first. Don't guess from `/usr/bin/java`, which is a chain of symlinks:

```bash
dirname "$(dirname "$(readlink -f "$(command -v javac)")")"

```

On my Ubuntu box that printed `/usr/lib/jvm/java-21-openjdk-amd64`. Fedora and RHEL use names like `/usr/lib/jvm/java-21-openjdk`. If `javac` isn't found, you don't have a JDK installed yet.

For your own user, put this in `~/.profile` (read by login shells and most desktop sessions), and source it from `~/.bashrc` if you want new terminal tabs to have it too:

```bash
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
export PATH="$JAVA_HOME/bin:$PATH"

```

For every user on the machine, put the same two lines in `/etc/profile.d/jdk.sh`. Remember that's login shells only. For a service, set it in the unit, because profile files don't apply there:

```bash
sudo systemctl edit myapp.service
# add, then save:
# [Service]
# Environment=JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64

```

For cron, set it at the top of the crontab (`JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64` on its own line), or export it inside the script the job runs. And for `sudo`, either use `sudo -E` (if your sudoers policy allows it) or pass it on the command line: `sudo JAVA_HOME="$JAVA_HOME" ./install.sh`.

### macOS

macOS ships a helper that knows where every installed JDK is: `/usr/libexec/java_home`. List what it sees, then pick one:

```bash
/usr/libexec/java_home -V          # every JVM it knows, printed to stderr
/usr/libexec/java_home -v 21       # path for a JDK 21

```

Put the export in `~/.zshrc` (zsh is the default shell on current macOS):

```bash
export JAVA_HOME=$(/usr/libexec/java_home -v 21)
export PATH="$JAVA_HOME/bin:$PATH"

```

The path it returns ends in `Contents/Home`, something like `/Library/Java/JavaVirtualMachines/<jdk>.jdk/Contents/Home`. That's correct. Don't trim it to the `.jdk` folder, which has no `bin` directly inside.

The gotcha I'd warn a teammate about: per Apple's man page, if no installed JVM matches `-v`, java\_home falls back to the default JVM rather than failing. Ask for 17 with only 21 installed and you quietly get 21\. Add `-F` (`java_home -F -v 17`) and it fails instead, which is what you want in a script. And a Homebrew `openjdk` is keg-only, so java\_home won't list it until you create the symlink into `/Library/Java/JavaVirtualMachines` that `brew info openjdk` prints in its caveats.

### Windows

First find the folder. Temurin's MSI installs to `C:\Program Files\Eclipse Adoptium\` with a version-named folder under it; Oracle's goes under `C:\Program Files\Java\`. The folder you want is the one containing `bin\java.exe`, not `bin` itself.

The GUI way: Start, type "environment", open "Edit the system environment variables", click Environment Variables, and add `JAVA_HOME` under User variables (or System variables, which needs admin). Paste the path without quotes, even though it contains spaces. Then edit `Path` in the same dialog and add `%JAVA_HOME%\bin` near the top.

The scriptable way, in PowerShell, for your user:

```powershell
$jdk = 'C:\Program Files\Eclipse Adoptium\<your-jdk-folder>'
[Environment]::SetEnvironmentVariable('JAVA_HOME', $jdk, 'User')

```

Use `'Machine'` instead of `'User'` from an elevated prompt for all users. You'll see `setx JAVA_HOME "..."` suggested a lot; it's fine for JAVA\_HOME, but don't use `setx` to rewrite `PATH`, because cmd expands the `%PATH%` you hand it first, which copies the system entries into your user `Path`, and `setx` truncates anything over 1024 characters.

If you install Temurin, its MSI can do this for you. Per Adoptium's docs, the "Set JAVA\_HOME variable" feature (`FeatureJavaHome`) is off by default while "Add to PATH" is on, so most people never tick it. For silent installs, the docs list `ADDLOCAL=FeatureMain,FeatureEnvironment,FeatureJarFileRunWith,FeatureJavaHome`.

Then open a *new* terminal and run `echo %JAVA_HOME%` (cmd) or `$env:JAVA_HOME` (PowerShell), and restart your IDE. If `java` itself still isn't found, that's the separate [PATH problem on Windows](https://ggorantala.dev/java-not-recognized-internal-external-command/?ref=ggorantala.dev).

### Containers and CI

The official `eclipse-temurin` images already set `JAVA_HOME=/opt/java/openjdk` with `ENV`, which every process in the container inherits. If you build your own image, do the same with `ENV` in the Dockerfile rather than an `export` in a `RUN` line; each `RUN` gets a fresh shell, so the export dies with it. In CI, the setup actions for Java (GitHub's `actions/setup-java`, for example) set JAVA\_HOME for later steps, so don't overwrite it in a step script.

## What I'd do instead

Hard-coding `/usr/lib/jvm/java-21-openjdk-amd64` works until somebody upgrades. The setup I keep on machines I own derives JAVA\_HOME from the `javac` that `PATH` finds, so the two can never disagree:

```bash
# ~/.profile — one source of truth: whichever javac is first on PATH
if command -v javac >/dev/null 2>&1; then
  JAVA_HOME="$(dirname "$(dirname "$(readlink -f "$(command -v javac)")")")"
  export JAVA_HOME
fi

```

On Debian and Ubuntu that means `update-alternatives --config javac` switches both at once. On macOS the `java_home -v` line already does the same job. If you switch versions all day, a version manager like SDKMAN (which points JAVA\_HOME at `~/.sdkman/candidates/java/current`) beats editing files by hand. For builds, I go one step further and stop relying on JAVA\_HOME for the compiler version at all: Maven Toolchains or Gradle's Java toolchains pin the JDK in the build file, so a laptop with the wrong JAVA\_HOME still compiles for the right release.

## Catching it before CI does

Put the check from earlier at the top of any build or deploy script, so a bad value fails in the first second with a message that names the problem:

```bash
: "${JAVA_HOME:?JAVA_HOME is not set}"
[ -x "$JAVA_HOME/bin/javac" ] || { echo "JAVA_HOME=$JAVA_HOME has no bin/javac (JRE, or points at bin?)" >&2; exit 1; }
"$JAVA_HOME/bin/java" -version

```

Running `mvn -v` or `gradle -v` as the first CI step helps too. Both print the Java version and the runtime path they picked, which is the cheapest audit you'll ever get.

On versions: JAVA\_HOME behaves the same on JDK 8 through 25, because the JDK itself has never read it. What changes is the folder name after an upgrade (a new `jdk-25...` directory on Windows, a new `.jdk` bundle on macOS). A hard-coded path keeps pointing at the old JDK, or at nothing once it's uninstalled. Re-run the comparison from the second section after every JDK upgrade.

## Takeaways

- JAVA\_HOME is the folder that *contains* `bin`. Pointing it at `bin` is the most common mistake, and Gradle will tell you so.
- The `java` command ignores JAVA\_HOME; `PATH` picks the `java` you run. Make them agree by putting `$JAVA_HOME/bin` first on `PATH`.
- `~/.bashrc` isn't read by cron, `bash -c`, sudo or systemd. Set it where the process that needs it actually looks.
- On macOS, use `java_home -F -v <version>` so a missing JDK fails loudly instead of quietly giving you a different one.
- Windows windows don't refresh. Open a new terminal and restart the IDE after changing it.

## Questions people search for

### How do I check if JAVA\_HOME is set correctly?

Run `echo $JAVA_HOME` (or `echo %JAVA_HOME%` in cmd), then `"$JAVA_HOME/bin/javac" -version`. If the second command works, it points at a JDK. Compare it with the `java.home` line from `java -XshowSettings:properties -version` to make sure your terminal and your build use the same JDK.

### Should JAVA\_HOME include the bin folder?

No. Use the JDK's root folder, like `/usr/lib/jvm/java-21-openjdk-amd64` or `C:\Program Files\Eclipse Adoptium\<jdk-folder>`. Tools append `bin` themselves, and Gradle reports "JAVA\_HOME is set to an invalid directory" when you include it.

### Where do I set JAVA\_HOME permanently on Linux?

For your user, `~/.profile` (and source it from `~/.bashrc` for terminal tabs). For all users, `/etc/profile.d/jdk.sh`. For services, the systemd unit's `Environment=` line, because services never read profile files. `/etc/environment` also works for logins, but it doesn't expand variables, so write the full path.

### How do I set JAVA\_HOME on macOS with java\_home?

Add `export JAVA_HOME=$(/usr/libexec/java_home -v 21)` to `~/.zshrc` and open a new terminal. Run `/usr/libexec/java_home -V` to see which JDKs it knows about, and add `-F` if you'd rather get an error than a fallback when the version you ask for isn't installed.