Install and Switch multiple versions of Java JDK on Linux or MacOS
While working on enterprise level, we often have java projects running on older versions of java for legacy reasons. Hence it is not very uncommon for a developer to have multiple versions of JDK installed in their machines and easy way to switch different versions of JDK on demand for running the build. This blog explains the steps needed to setup and configure multiple JDK versions on Mac OS.
Get the architecture of the Machine from Terminal using:
uname -m
Create a directory for installation:
mkdir -p $HOME/tools/java
Download java binaries:
Download java 25 and 21 binary for Linux / Mac OS operating system with the correct architecture type to directory $HOME/tools/java
Extract and rename java binaries:
find $HOME/tools/java -type f -name OpenJDK25*.tar.gz | xargs -I {} mv {} $HOME/tools/java/OpenJDK25.tar.gz
find $HOME/tools/java -type f -name OpenJDK21*.tar.gz | xargs -I {} mv {} $HOME/tools/java/OpenJDK21.tar.gz
tar -xvzf $HOME/tools/java/OpenJDK25.tar.gz -C $HOME/tools/java
tar -xvzf $HOME/tools/java/OpenJDK21.tar.gz -C $HOME/tools/java
find $HOME/tools/java -type d -name jdk-25* | xargs -I {} mv {} $HOME/tools/java/jdk-25
find $HOME/tools/java -type d -name jdk-21* | xargs -I {} mv {} $HOME/tools/java/jdk-21
Make the extracted binaries as executables:
chmod a+rwx -R $HOME/tools/java/*
Identify the shell used in the Terminal using:
echo $SHELL
Configure PATH:
Add the following lines to $HOME/.bash_profile or $HOME/.bashrc or $HOME/.zprofile based on the shell used by the Terminal and the changes will take effect after system restart
# setting java homes
export JAVA_25_HOME=$HOME/tools/java/jdk-25
export JAVA_21_HOME=$HOME/tools/java/jdk-21
# setting alias to switch java version
alias java25='export JAVA_HOME=$JAVA_25_HOME && export PATH=$JAVA_25_HOME/bin:$PATH'
alias java21='export JAVA_HOME=$JAVA_21_HOME && export PATH=$JAVA_21_HOME/bin:$PATH'
# setting default version to latest version of java
export JAVA_HOME=$JAVA_25_HOME
export PATH=$JAVA_25_HOME/bin:$PATH
Temporarily source the changes:
source $HOME/.bash_profile
or
source $HOME/.zprofile
Verify default java version:
java -version
Swith to old version of java:
java21
java -version
Switch to new version of java:
java25
java -version
Setup IDE SDK:
In the IDE (IntelliJ) add the SDK location as $HOME/tools/java/jdk-25 or $HOME/tools/java/jdk-21 based on the project's source code version
Comments
Post a Comment