If you are working on multiple java projects or multiple tools that requires java, You might need to switch between multiple java versions often. This blog helps you to switch between different java version easily.
Installing Multiple Java
Install two or more java as per your requirements. Here I installed Java 8 and Java 11.
Add %JAVA_HOME%\bin value in path environment variable.
Important: Don't add JAVA_HOME environment variable. Batch script will handle this environment variable.
Batch Script
Copy below batch script and save it with the extension of .bat at your convenient location. I placed this batch script at my desktop.
@echo off
REM =========ADD YOUR JAVA HOME==============
set Arr[0]=C:\Program Files\Java\jdk1.8.0_241
set Arr[1]=C:\Program Files\Java\jdk-11.0.8
REM =========================================
set "x=0"
set "choice=1"
echo Existing Path: %JAVA_HOME%
echo Choose Your Java Version:
REM ==========Printing Choices Starts========
:SymLoop
if not defined Arr[%x%] goto :endLoop
call set VAL=%%Arr[%x%]%%
echo [%choice%]. %VAL%
REM do your stuff VAL
SET /a "x+=1"
SET /a "choice+=1"
GOTO :SymLoop
:endLoop
echo [x]. Exit / Cancel
REM ==========Printing Choices Ends==========
REM ==========Getting Choices From User======
:choice
SET /P C=Your Choice:
SET /a "C=C-1"
REM ==========Validating Input Starts=========
if not defined Arr[%C%] goto :byebye
for %%? in (C) do if /I "%C%"=="%%?" goto :byebye
REM ==========Validating Input Ends===========
REM ==========Setting Environment=============
@echo off
call set NEW_PATH=%%Arr[%C%]%%
echo Setting path: %NEW_PATH%
setx JAVA_HOME "%NEW_PATH%"
REM ==========Setting Environment Done=========
:byebye
echo Done.
pause
Edit the batch script in your text editor and add your Java home location as like below.
Save the file and run the script
Select your Java version choice in the command prompt.
That's it. Now open another command prompt and enter command java -version