> ## 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 Switch Between Java Versions with Several JDKs Installed
- URL: https://www.ggorantala.dev/switch-java-versions-multiple-jdks/
- Published: 2026-11-30T17:33:59.000Z
- Updated: 2026-11-30T17:33:59.000Z
- Description: Switching between Java 17, 21 and 25 means moving java, javac and JAVA_HOME together, and often you don't need to switch at all. The commands for SDKMAN, jenv, java_home, alternatives and Windows, plus the javac --release trick.
- Author: Gopi Gorantala
- Tags: switch-java-versions, sdkman, update-alternatives, java-home, javac-release, jdk-setup, macos, linux

Here's the verdict first, because it saves most people an afternoon: when you switch between Java versions, you're changing three separate things, and most switching tools only change one of them. The `java` your shell runs. The `javac` that compiles. And `JAVA_HOME`, which Maven, Gradle and your IDE read instead of either. Move one without the others and you get a laptop that runs 21, compiles with 17 and builds with whatever `JAVA_HOME` pointed at last Tuesday.

The second half of the verdict: a lot of the time you don't need to switch at all.

## What switching actually changes

Say you've got JDK 17 for the nightly reconciliation job, 21 for everything new, and 25 because you wanted to try it. The question is how to flip between them per terminal, per project, or for the whole machine, without leaving half the toolchain behind.

Three things decide "which Java" on a machine, and they don't talk to each other:

| What          | Who reads it                            | How it's picked                                     |
| ------------- | --------------------------------------- | --------------------------------------------------- |
| java on PATH  | your shell, scripts, java -jar          | first match on PATH, or the /usr/bin/java link      |
| javac on PATH | builds run by hand, some IDE setups     | same lookup, but a separate link on Linux           |
| JAVA\_HOME    | Maven, Gradle, IDEs, app-server scripts | an environment variable, whatever was exported last |

If you're here because `java -version` refuses to change at all, that's a `PATH` order problem, and [the post on the wrong Java version running](https://ggorantala.dev/wrong-java-version-path-order/?ref=ggorantala.dev) covers it. This one assumes the lookup works and you want to change the answer on purpose.

## Check all three before you touch anything

```bash
java -XshowSettings:properties -version 2>&1 | grep java.home   # the java that really runs
readlink -f "$(command -v javac)"                                # the javac that really compiles
echo "$JAVA_HOME"                                                # what your build tools will use

```

On Windows, `where.exe java`, `where.exe javac` and `echo %JAVA_HOME%` give you the same three answers. If those three lines don't name the same JDK folder, you're not on one version. You're on two or three.

## Watching a switch go half-way

I couldn't download a second JDK version in my sandbox for this one (the package mirrors were blocked), so I built the lab around what was there: OpenJDK 21.0.13.1 on Ubuntu 24.04, plus a second, cut-down runtime made from it with `jlink`. Same version number, but a different folder and no compiler, which turns out to be exactly what you need to see the problem.

### Step 1: make a second Java install

```bash
J21=/usr/lib/jvm/java-21-openjdk-amd64
$J21/bin/jlink --add-modules java.base,java.logging \
  --output /opt/jre-21-slim --strip-debug --no-header-files --no-man-pages
ls /opt/jre-21-slim/bin

```

```log
java
keytool

```

### Step 2: register it with alternatives and switch to it

```log
$ update-alternatives --install /usr/bin/java java /opt/jre-21-slim/bin/java 100
$ update-alternatives --list java
/opt/jre-21-slim/bin/java
/usr/lib/jvm/java-21-openjdk-amd64/bin/java
$ update-alternatives --set java /opt/jre-21-slim/bin/java
update-alternatives: using /opt/jre-21-slim/bin/java to provide /usr/bin/java (java) in manual mode

```

### Step 3: check the three things again

```log
$ java -XshowSettings:properties -version 2>&1 | grep java.home
    java.home = /opt/jre-21-slim
$ readlink -f $(command -v javac)
/usr/lib/jvm/java-21-openjdk-amd64/bin/javac
$ echo $JAVA_HOME
[/usr/lib/jvm/java-21-openjdk-amd64]

```

There it is. `java` moved. `javac` didn't, because on Debian and Ubuntu `javac` is its own alternatives group. `JAVA_HOME` didn't either, because `update-alternatives` never touches environment variables. With two real versions, say 17 and 21, that's the classic "my terminal says 17, my Gradle build says 21" afternoon.

### Step 4: undo it

```log
$ update-alternatives --auto java
update-alternatives: using /usr/lib/jvm/java-21-openjdk-amd64/bin/java to provide /usr/bin/java (java) in auto mode
$ update-alternatives --remove java /opt/jre-21-slim/bin/java

```

Auto mode picks the highest priority. Ubuntu's OpenJDK 21 package registered itself at 2111; my slim runtime was 100\. Then `rm -rf /opt/jre-21-slim`.

## The short answer

Pick one tool to own the switch, and make it move `java`, `javac` and `JAVA_HOME` together. Version managers do that because they put one directory on `PATH` and repoint it. Hand-rolled exports do it if you write them carefully. `update-alternatives` alone doesn't.

## Why the half-switch happens

My first guess, before the lab, was that `update-alternatives --config java` was the "proper" Linux way and everything else was a hack. It's the proper way to choose the machine's default `/usr/bin/java`. It was never designed to set `JAVA_HOME`, and `javac`, `jar`, `jshell` and friends each have their own group, so on a box with five JDKs you'd run `--config` for every tool. On Fedora and RHEL the command is `alternatives`, and `JAVA_HOME` is still yours to set.

The second dead end was the shell function everyone writes first:

```bash
usejava() { export JAVA_HOME="$1"; export PATH="$JAVA_HOME/bin:$PATH"; }

```

It works. Then you call it six times in one terminal session and look at your `PATH`:

```log
      1 /bin
      3 /opt/jre-21-slim/bin
      1 /usr/bin
      3 /usr/lib/jvm/java-21-openjdk-amd64/bin

```

That's from six calls alternating between two JDKs. The newest one still wins, so nothing breaks yet, but `PATH` grows every call and `type -a java` turns into a list of every JDK you ever touched. The version that strips the old entry first is below.

Version managers sidestep all of it. SDKMAN! puts one entry on `PATH`, `~/.sdkman/candidates/java/current/bin` (or the specific version's folder after `sdk use`), and sets `JAVA_HOME` to match. jenv puts a shims folder on `PATH` and decides per directory which JDK the shims call. Nothing piles up.

And the surprise, which I'll get to properly in a minute: the reason most people switch is to build for an older Java, and `javac` has had a flag for that since JDK 9.

## How to switch, per OS and per tool

### Linux and macOS with SDKMAN!

```bash
sdk list java                         # installed and available builds, with identifiers
sdk install java 17.0.17-tem          # identifier comes from 'sdk list java'
sdk use java 17.0.17-tem              # this terminal only
sdk default java 21.0.9-tem           # new terminals from now on
sdk current java                      # what this shell is using

```

Take the exact identifiers from `sdk list java` on your machine; the patch numbers above will be stale by the time you read this. For per-project versions, run `sdk env init` in the project folder. It writes a `.sdkmanrc` with `java=<identifier>`, `sdk env` switches to it, and setting `sdkman_auto_env=true` in `~/.sdkman/etc/config` makes `cd` do it for you. The [SDKMAN! usage page](https://sdkman.io/usage?ref=ggorantala.dev) has the full list. On Windows, SDKMAN! runs under WSL, not in cmd or PowerShell.

### macOS without a version manager

```bash
/usr/libexec/java_home -V                     # every JDK in /Library/Java/JavaVirtualMachines
export JAVA_HOME=$(/usr/libexec/java_home -v 17)
export PATH="$JAVA_HOME/bin:$PATH"

```

On a Mac, the `/usr/bin/java` stub reads `JAVA_HOME`, so setting it changes what `java` runs, which isn't true on Linux. Homebrew's `openjdk@17` is keg-only and won't show up in `java_home -V` until you create the symlink its install notes print.

### macOS or Linux with jenv

```bash
jenv add /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home
jenv versions
jenv global 21          # machine default
jenv local 17           # writes .java-version in this folder
jenv enable-plugin export   # without this, JAVA_HOME doesn't follow

```

jenv doesn't install JDKs, it only registers ones you already have. And that last line is the one people skip, which brings back the half-switch from the lab: `java` follows `.java-version`, Maven doesn't. Details are in the [jenv README](https://github.com/jenv/jenv?ref=ggorantala.dev).

### Linux by hand, without the PATH pile-up

```bash
usejava() {
  local new="$1"
  PATH=$(printf '%s' "$PATH" | tr ':' '\n' | grep -v "^${JAVA_HOME:-/nonexistent}/bin$" | paste -sd: -)
  export JAVA_HOME="$new" PATH="$new/bin:$PATH"
  hash -r
}
usejava /usr/lib/jvm/java-17-openjdk-amd64

```

After the same six alternating calls, my `PATH` was back to `/usr/lib/jvm/java-21-openjdk-amd64/bin:/usr/bin:/bin`. The `hash -r` matters: bash caches where it found `java` last time.

### Windows

There's no built-in switcher. The setup that stays sane is one `%JAVA_HOME%\bin` entry in the **system** `Path`, no Oracle `javapath` above it, and you switch by changing `JAVA_HOME` in System Properties, then opening a new terminal. For one window only:

```bat
:: cmd
set "JAVA_HOME=C:\Program Files\Eclipse Adoptium\jdk-17.0.17.10-hotspot"
set "PATH=%JAVA_HOME%\bin;%PATH%"

```

```powershell
# PowerShell
$env:JAVA_HOME = 'C:\Program Files\Eclipse Adoptium\jdk-17.0.17.10-hotspot'
$env:Path = "$env:JAVA_HOME\bin;$env:Path"

```

Use your real folder name; the one above is an example. Don't use `setx PATH "%PATH%;..."` for this: `%PATH%` is the merged user-plus-system value, so you copy the system entries into your user `Path`, and `setx` truncates anything past 1,024 characters. If you install JDKs through Scoop, `scoop reset <jdk-package>` repoints its shims. I didn't run any of the Windows commands for this post; they're straight from how `cmd` and PowerShell handle environment variables.

## Often you don't need to switch: javac --release

Most switching happens because a project targets an older Java. You don't need that older JDK to compile for it. Since JDK 9, `javac --release N` compiles against the exact public API of release N and writes class files for it. Here's a small file from the reconciliation job, compiled on JDK 21:

```java
import java.util.ArrayList;
import java.util.List;

public class Lab {
    public static void main(String[] args) {
        List<String> runs = new ArrayList<>(List.of("eod-batch", "fx-rates", "recon"));
        System.out.println(runs.getLast()); // SequencedCollection, added in JDK 21
        System.out.println(System.getProperty("java.version"));
    }
}

```

```log
$ javac --release 17 -d out17 Lab.java
Lab.java:7: error: cannot find symbol
        System.out.println(runs.getLast()); // SequencedCollection, added in JDK 21
                               ^
  symbol:   method getLast()
  location: variable runs of type List<String>
1 error

```

That's the check you want. Now the old way, with `-source` and `-target`:

```log
$ javac -source 17 -target 17 -d outst Lab.java
warning: [options] system modules path not set in conjunction with -source 17
1 warning
$ javap -v -cp outst Lab | grep major
  major version: 61

```

It compiled. A class file stamped for Java 17 (major version 61) that calls a method Java 17 doesn't have. That's a `NoSuchMethodError` waiting on whichever server still runs 17\. I couldn't run it on a real 17 here, but the method isn't in 17's `List`, so there's nothing else it can do. After replacing `getLast()` with `get(runs.size() - 1)`, `--release 17` compiled cleanly, also major version 61, and ran on 21 printing `recon` and `21.0.13.1`.

One limit: JDK 21's `javac` dropped `--release 7` (`error: release version 7 not supported`) and warns that 8 is obsolete. For anything older than 8 you need the old JDK.

In builds, say it once and stop depending on the shell:

```xml
<properties>
  <maven.compiler.release>17</maven.compiler.release>
</properties>

```

```kotlin
// build.gradle.kts
java { toolchain { languageVersion = JavaLanguageVersion.of(17) } }

```

Gradle's toolchain finds (or provisions) a 17 regardless of `JAVA_HOME`. Maven's equivalent for running tests on the real 17 is the Toolchains plugin with a `~/.m2/toolchains.xml`.

## Proving you landed where you meant to

Put the three-line check from the top into a script and run it after every switch until it's habit. In CI, fail fast:

```bash
java -version 2>&1 | grep -q '"17\.' || { echo "expected Java 17, got:"; java -version; exit 1; }
[ "$(readlink -f "$JAVA_HOME/bin/java")" = "$(readlink -f "$(command -v java)")" ] \
  || { echo "JAVA_HOME and PATH disagree"; exit 1; }

```

Version safety: none of the switching mechanics changed between JDK 8 and 25; they belong to your shell, OS and version manager. What does change is folder names on every update (`jdk-17.0.16` to `jdk-17.0.17`), so point `JAVA_HOME` at a stable symlink or a version manager's `current`, and re-check `update-alternatives --query java` after any package upgrade. The thing to re-check when you move `javac` up a release is which old `--release` values it still accepts.

## Worth keeping

- "Which Java" is three answers: `java` on `PATH`, `javac` on `PATH`, and `JAVA_HOME`. A switch that moves one is half a switch.
- `update-alternatives` chooses `/usr/bin/java` and nothing else. Not `javac`, not `JAVA_HOME`.
- Let one tool own it: SDKMAN!, jenv with the export plugin, or a function that removes the old entry before adding the new one.
- Building for 17 on a 21 JDK? `javac --release 17` (or `maven.compiler.release`, or a Gradle toolchain), not `-source`/`-target`.

## Questions people search for

### How do I switch between Java versions on Mac?

Run `/usr/libexec/java_home -V` to list installed JDKs, then `export JAVA_HOME=$(/usr/libexec/java_home -v 17)` and put `$JAVA_HOME/bin` first on `PATH`. For per-project switching, SDKMAN! (`.sdkmanrc`) or jenv (`.java-version`, with `jenv enable-plugin export`) do it automatically when you change directory.

### How do I change the default Java version in Ubuntu?

`sudo update-alternatives --config java` and pick the JDK, then do the same for `javac`, which is a separate group. That sets the machine default but not `JAVA_HOME`, so also update the line in `/etc/environment` or your shell profile, as covered in [setting JAVA\_HOME](https://ggorantala.dev/set-java-home-windows-macos-linux/?ref=ggorantala.dev).

### Can I have Java 17 and 21 installed at the same time?

Yes, any number of JDKs can sit side by side in their own folders. The only thing that's single-valued is which one each tool picks, so decide who owns that choice and check `java.home` after switching.

### Do I need an older JDK to compile for an older Java version?

Usually not. `javac --release 17` on JDK 21 compiles against Java 17's API and produces Java 17 class files, and it rejects calls to methods 17 doesn't have. You still want the real older JDK to run your tests, and JDK 21's `javac` no longer accepts `--release 7`.