How to Switch Between Different Java Versions on Mac
To switch between different versions of Java on your Mac, you can use the jenv
tool in combination with Homebrew. Here’s a step-by-step guide:
1 - Install jenv using Homebrew by running the following command in Terminal:
$ brew install jenv
2 - Once the installation is complete, you need to initialize jenv
. Run the following command to add jenv
to your shell:
$ echo 'eval "$(jenv init -)"' >> ~/.bash_profile
If you’re using a different shell (such as Zsh), replace ~/.bash_profile
with the appropriate configuration file (e.g., ~/.zshrc
).
3 - Restart your Terminal or run the following command to apply the changes:
$ source ~/.bash_profile
4 - Now, you can install different versions of Java using Homebrew. For example, to install AdoptOpenJDK version 11, run:
$ brew install --cask adoptopenjdk@11
You can install multiple versions of Java using this command.
5 - After installing different Java versions, you need to let jenv
know about them. Run the following command for each installed version:
$ jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
Replace the path with the correct path to the Java installation directory of each version.
6 - To see the list of installed Java versions, run:
$ jenv versions
You should see a list of installed Java versions.
7 - Set a global Java version using jenv by running the following command:
$ jenv global 11.0
Replace 11.0 with the version number you want to set as the default.
8 - To verify the currently active Java version, run:
$ java -version
The displayed version should match the one you set using jenv
.
That’s it! You have successfully switched between different versions of Java using jenv
. You can set a different version as the default or configure Java version per directory using jenv local
command. Refer to the jenv documentation for more information on advanced usage and configuration options.