How to set or change the default Java (JDK) version on macOS?
To swiftly configure your desired Java version, execute:
Replace [version_number] with versions like 1.8, 11, etc. You can verify your switch with:
To have the version locked, add the export line to your ~/.bash_profile if you're a Bash user or ~/.zshrc for Zsh users.
Quick Session vs Permanent JDK Change
For an ephemeral session JDK switch, your terminal command suffices. But if you need your changes to persist, you should modify your shell's initialization script.
Bash users can use:
And for Zsh users:
Validate the update by running echo $JAVA_HOME.
Streamlined Version Switching
Shift between JDK versions efficiently by employing aliases or functions in your shell profile.
Set an alias per version:
Or, a develop a function named jhome for dynamic JAVA_HOME setting:
Copy-paste java11 or jhome 11 for switching.
Project-specific JDK Setting
Designate a distinct JDK for separate projects or sessions without affecting the system-wide default. Set the JAVA_HOME within your session or script related to that environment.
For a one-time session:
For an individual project, add the command to its startup script.
JDK Management Tools
Managing multiple JDK versions? jenv or SDKMAN! might be your saviors! These tools streamline the process of switching and maintaining Java environments.
Install JDKs with Homebrew:
Manage JDKs using:
Or, with SDKMAN!:
Don't forget to untap outdated casks periodically:
Troubleshooting Common Issues
Experiencing unresponsive commands or misidentification of versions? This should help:
- If
java_homeomits versions, checkInfo.plistfiles under/Library/Java/JavaVirtualMachines. - JDK paths might change post system updates, recheck them.
- Make sure multiple
JAVA_HOMEdeclarations aren't conflicting in your profile scripts.
Was this article helpful?