Manage several Java versions on MacOS
Managing multiple Java versions on MacOS can be a bit tricky, especially when different projects require different versions of Java. However, it can be done smoothly with the right tools and setup. Here, I'll walk you through the steps to manage several Java versions on MacOS using Homebrew and some simple configuration in your shell.
Step 1: Install Homebrew
First, if you haven't already, you'll need to install Homebrew. Homebrew is a package manager for MacOS that makes it easy to install and manage software.
To install Homebrew, open your terminal and run:
/bin/bash -c "$(curl -fsSL <https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh>)"
Step 2: Install Java Versions
Next, you can use Homebrew to install the different versions of Java you need. For this example, I'll install Java 8, Java 11, Java 17, and Java 21.
brew install --cask temurin@8
brew install --cask temurin@11
brew install --cask temurin@17
brew install --cask temurin@21
Step 3: Configure Environment Variables
After installing the Java versions, you'll need to configure your shell to switch between them easily. This can be done by editing your .zshrc
file (or .bashrc
if you're using bash).
Add the following lines to your .zshrc
file:
export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)
export JAVA_17_HOME=$(/usr/libexec/java_home -v17)
export JAVA_21_HOME=$(/usr/libexec/java_home -v21)
alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'
alias java17='export JAVA_HOME=$JAVA_17_HOME'
alias java21='export JAVA_HOME=$JAVA_21_HOME'
# default to java21
export JAVA_HOME=$JAVA_21_HOME
These lines set up environment variables for each Java version and create aliases to switch between them.
Step 4: Reload Your Shell Configuration
After editing your .zshrc
file, you'll need to reload it to apply the changes. You can do this by running:
source ~/.zshrc
Step 5: Switch Between Java Versions
Now, you can easily switch between different Java versions by using the aliases you've set up. For example, to switch to Java 17, you would run:
java17
You can verify the Java version by running:
java --version
You should see output similar to:
openjdk 17.0.11 2024-04-16
...
Conclusion
By following these steps, you can manage multiple Java versions on MacOS without any hassle. This setup allows you to switch between Java versions quickly, ensuring that you can work on different projects that require different versions of Java seamlessly. Surely, this is not the only way to manage Java versions on MacOS, but this is the one I found the most comfortable using. Happy coding!