Install Java on macOS
Introduction
On macOS the practical path is Homebrew: one command installs a current OpenJDK, and switching versions is a matter of installing another formula side by side.
Install a JDK
brew install openjdk@17
Homebrew kegs the JDK without linking it into the system paths. Link it for the macOS java wrapper:
sudo ln -sfn /opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-17.jdk
JAVA_HOME
The wrapper resolves the JDK itself, but Maven and Gradle still read JAVA_HOME:
export JAVA_HOME=$(/usr/libexec/java_home -v 17)
Add the line to ~/.zshrc to keep it in every new terminal.
Check the version
java -version
Both java and javac must report the installed release.
Multiple versions side by side
Install several casks (openjdk@17, openjdk@21) and switch with /usr/libexec/java_home -v plus a shell alias per version. Never overwrite the system java stub in /usr/bin — macOS guards it, and fighting the guard breaks updates.