Post

Change the default Java (JDK) version on macOS

First run /usr/libexec/java_home -V to check available Java Virtual Machine:

1
2
3
4
Matching Java Virtual Machines (2):
20.0.1 (arm64) "Eclipse Adoptium" - "OpenJDK 20.0.1" /Library/Java/JavaVirtualMachines/temurin-20.jdk/Contents/Home
17.0.7 (arm64) "Eclipse Adoptium" - "OpenJDK 17.0.7" /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/temurin-20.jdk/Contents/Home

Change the default Java (JDK) version

Pick the version you want to be the default (20.0.1) then:

export JAVA_HOME="/usr/libexec/java_home -v 20.0.1"

Now when you run java -version you will see:

1
2
3
openjdk version "20.0.1" 2023-04-18
OpenJDK Runtime Environment Temurin-20.0.1+9 (build 20.0.1+9)
OpenJDK 64-Bit Server VM Temurin-20.0.1+9 (build 20.0.1+9, mixed mode)

Add the

1
2
export JAVA_HOME="/usr/libexec/java_home -v 20.0.1"

line to your shell’s init file.

Updating the .zshrc file should work:

1
2
nano ~/.zshrc

paste the line

1
2
export JAVA_HOME=$(/usr/libexec/java_home -v 20.0.1)

at bottom of the file.

Press CTRL+X to exit the editor, Press Y to save your changes.

1
2
3
source ~/.zshrc
echo $JAVA_HOME
java -version

Fast switch between different JDK versions

  1. Add the below function in your ~/.bashrc or ~/.zshrc
1
2
3
4
5
jdk() {
        version=$1
        export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
        java -version
 }
  1. Source the profile and you can change the version like below:
1
2
 jdk 17
 jdk 20

References

This post is licensed under CC BY 4.0 by the author.