Skip to content

Instantly share code, notes, and snippets.

@krishnanunnijs
Last active August 9, 2024 17:26
Show Gist options
  • Save krishnanunnijs/b7d0356749e522d88f1c3b490668f417 to your computer and use it in GitHub Desktop.
Save krishnanunnijs/b7d0356749e522d88f1c3b490668f417 to your computer and use it in GitHub Desktop.

Switch Between Multiple Java Versions on Windows

How to Use the Script:

  • Save the script: Create a .bat file using the the script below and save it as usedjk.bat.

  • Move the bat file in environment path : Add the script path to user/system environment variable (optional)

  • Run the script: Open Command Prompt and navigate to the directory where you saved the script. (if #2 is not done)

  • Switch Java versions: Run the script with the desired Java version as an argument.

    For example: usejdk 8 usejdk 11

Script

@echo off

:: Define the paths to your Java installations
set JAVA8_HOME=C:\Program Files\Java\jdk1.8.0_321
set JAVA11_HOME=C:\Program Files\Java\jdk11.0.15_9
set JAVA17_HOME=C:\Program Files\Java\jdk17.0.6_10

:: Function to set the Java version
:SET_JAVA_VERSION
if "%1"=="8" (
    set JAVA_HOME=%JAVA8_HOME%
) else if "%1"=="11" (
  set JAVA_HOME=%JAVA11_HOME%
) else if "%1"=="17" (
   set JAVA_HOME=%JAVA17_HOME%
) else (
   #echo Invalid Java version specified. Use 8, 11, or 17.
   set JAVA_HOME=%JAVA8_HOME%`
    goto :EOF
    )

echo Switched to Java "%1"
set PATH=%JAVA_HOME%\bin;%PATH%

:: Verify the switch
java -version

goto :EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment