To install Java on macOS and allow version switching, you can use the “Homebrew” package manager. Homebrew makes it easy to manage multiple versions of Java on your system and switch between them as needed. Here’s a step-by-step guide to do it:
1. Install Homebrew: If you don’t have Homebrew installed, open Terminal (you can find it in Applications > Utilities) and run the following command:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Follow the instructions during the installation process.
2. Install AdoptOpenJDK: Next, use Homebrew to install the jenv
tool and the AdoptOpenJDK versions you want. In this example, we’ll install AdoptOpenJDK 8, 11, and 16:
brew install jenv
brew tap AdoptOpenJDK/openjdk
brew install --cask adoptopenjdk8
brew install --cask adoptopenjdk11
brew install --cask adoptopenjdk16
3. Set up jenv: After the installations are completed, you need to set up jenv
. This will allow you to manage and switch between different Java versions easily.
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(jenv init -)"' >> ~/.bash_profile
If you’re using zsh
as your shell instead of bash
, replace .bash_profile
with .zshrc
in the above commands.
4. Configure jenv with installed JDKs: Now, let’s tell jenv
about the installed JDKs:
jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-16.jdk/Contents/Home
5. Choose the Java version: You can set the global Java version or choose a version for a specific directory/project. For example, to set the global Java version to JDK 11, run:
jenv global 11
To set the version for a specific directory, navigate to the directory, and run:
jenv local 8 # Or any other version you prefer
6. Verify the Java version: To verify that everything is set up correctly, you can check the current Java version with the following commands:
java -version
This should display the version you selected with jenv
.
That’s it! You now have Java installed on your macOS with version switching capabilities. You can install other Java versions in the future and switch between them easily using jenv
.