Gradle somehow uses old JAVA_HOME value after JDK upgrade

When I invoke the Gradle wrapper in my project, I get this error:

FAILURE: Build failed with an exception.

* What went wrong:
The supplied javaHome seems to be invalid. I cannot find the java executable. Tried location: C:\Program Files\Eclipse Adoptium\jdk-17.0.11.9-hotspot\bin\java.exe

* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

However, the JAVA_HOME variable is set correctly.

$ echo $JAVA_HOME
C:\Program Files\Eclipse Adoptium\jdk-17.0.12.7-hotspot

Prior to this I upgraded JDK (Eclipse Temurin) from version jdk-17.0.11.9-hotspot to jdk-17.0.12.7-hotspot, updated JAVA_HOME and rebooted. But Gradle still somehow finds the old JDK, I’m not even sure how…

It turns out Gradle was confused by the presence of the old JDK directory in C:\Program Files\Eclipse Adoptium. For some reason it hasn’t been deleted by the installer. Is this expected behavior? I thought it’s supposed to use the JAVA_HOME var.

The --stacktrace or --scan URL would maybe be helpful to see where this was coming from.
The Gradle CLI uses JAVA_HOME and it successfully started as the messages you see are from Java code.