Switching between different JDK versions in Windows
Asked Answered
C

8

40

I'm working on few projects and some of them are using different JDK. Switching between JDK versions is not comfortable. So I was wondering if there is any easy way to change it?

I found 2 ways, which should solve this problem, but it doesn't work.

First solution is creating a bat files like this:

@echo off
echo Setting JAVA_HOME
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_72
echo setting PATH
set PATH=C:\Program Files\Java\jdk1.7.0_72\bin;%PATH%
echo Display java version
java -version
pause

And after running this bat, I see right version of Java. But when I close this CMD and open a new one and type "java -version" it says that I still have 1.8.0_25. So it doesn't work.

Second solution which I found is an application from this site. And it also doesn't work. The same effect as in the first solution.

Any ideas? Because changing JAVA_HOME and PAHT by: Win + Pause -> Advanced System Settings -> Environment Variables -> and editing these variables, is terrible way...

Chromolithography answered 18/11, 2014 at 11:22 Comment(2)
Set path with batch file, and execute java too inside batch file.Oscillograph
As you can see both variables are setting in batch file. But I don't know how to execute java inside this file. I found this solution on another page and I don't know how to write batch files.Chromolithography
C
52

The set command only works for the current terminal. To permanently set a system or user environment variable you can use setx.

You can set the variable for the current user like this:

setx JAVA_HOME "C:\Program Files\Java\jdk1.7.0_72"

You can also set the variable system wide (Note: The terminal must be run as administrator fo this) by running the same command with the /m option:

setx JAVA_HOME "C:\Program Files\Java\jdk1.7.0_72" /m

The variable will be available in all new terminal session, but not the current one. If you also want to use the path in the same sessoin, you need to use both set and setx.

You can avoid manipulating the PATH variable if you just once put %JAVA_HOME% in there, instead of the full JDK path. If you change JAVA_HOME, PATH will be updated too.


There are also a few environment variable editors as alternative to the cumbersome Windows environment variable settings. See "Is there a convenient way to edit PATH in Windows 7?" on Super User.

Carmen answered 18/11, 2014 at 11:29 Comment(8)
Hmmm something is wrong... I did as you said and it adds these variables, but for user... And still when I open new terminal I get info that I have different JDK than I want...Chromolithography
It was missing the /m option, I've updated the answer.Carmen
Do I also have to replace the second "set" with "setx" (line: set PATH=C:\Program Files\Java\jdk1.7.0_72\bin;%PATH%)?Defraud
@Defraud If you permanently want to change the PATH, you need to use setx there too. It will add the java path every time you run the script though, so it may be better to remove that line and to add %JAVA_HOME% to the PATH only onceCarmen
Terminal or application needs a restart to take into account changes in PATH caused by updated JAVA_HOME. Or #172088Parham
ERROR: Access to the registry path is denied.Snood
@Snood You'll get that error if you don't have permissions to set environment variables. You need to run cmd as administratorCarmen
@Carmen yeah, which I can't. The solution for me was to use the set and run it every time in my console session before doing anything. ThanksSnood
C
17

In case if someone want to switch frequently in each new command window then I am using following approach.

Command Prompt Version:

Create batch file using below code. You can add n number of version using if and else blocks.

@echo off
if "%~1" == "11" (
   set "JAVA_HOME=C:\Software\openjdk-11+28_windows-x64_bin\jdk-11"
) else (
   set "JAVA_HOME=C:\Program Files\Java\jdk1.8.0_151"
)
set "Path=%JAVA_HOME%\bin;%Path%"
java -version

Save this batch file as SJV.bat and add this file location in your machine's Path environment variable. So now SJV will act as command to "Switch Java Version".

Now open new command window and just type SJV 11 it will switch to Java 11. Type SJV 8 it will switch to Java 8.

PowerShell Version

Create powershell(ps1) file using below code. You can add n number of version using if and else blocks.

If($args[0] -eq "11")
{
    $env:JAVA_HOME = 'C:\Software\openjdk-11+28_windows-x64_bin\jdk-11'
}else{
    $env:JAVA_HOME = 'C:\Program Files\Java\jdk1.8.0_151'
}
$env:Path = $env:JAVA_HOME+'\bin;'+$env:Path
java -version

Save this script file as SJV.ps1 and add this file location in your machine's Path environment variable. So now SJV will act as command to "Switch Java Version".

Now open new powershell window and just type SJV 11 it will switch to Java 11. Type SJV 8 OR SJV it will switch to Java 8.

I hope this help someone who want to change it frequently.

Cofield answered 21/10, 2020 at 8:14 Comment(4)
Note to others: this works on the command line. But not powershellTrinl
@Trinl I have updated answer with PowerShell script also.Cofield
when I open other window and type "java -version", I get the old versionMyranda
In each window you need to run SJV command first with required java version like SJV 8 or SJV 11. Then it will give proper version.Cofield
G
12
  1. Open Environment Variables editor (File Explorer > right click on This PC > Properties > Advanced system settings > Environment Variables...)
  2. Find Path variable in System variables list > press Edit > put %JAVA_HOME%bin; at first position. This is required because Java installer adds C:\Program Files (x86)\Common Files\Oracle\Java\javapath to the PATH which references to the latest Java version installed. enter image description here
  3. Now you can switch between Java version using setx command (should be run under administrative permissions):

    setx /m JAVA_HOME "c:\Program Files\Java\jdk-10.0.1\
    

    (note: there is no double quote at the end of the line and should not be or you'll get c:\Program Files\Java\jdk-10.0.1\" in your JAVA_HOME variable and it breaks your PATH variable)

Solution with system variables (and administrative permissions) is more robust because it puts desired path to Java at the start of the resulting PATH variable.

Greening answered 6/7, 2018 at 19:58 Comment(1)
I tried this in Windows 10, it does not work, %JAVA_HOME%\bin is in path however java executable is not foundThomasson
T
3

Adding to the answer provided here (https://mcmap.net/q/396131/-switching-between-different-jdk-versions-in-windows).

I manually created environment variables via UI for Java11, Java17 and Java8. To change across Java version:

From powershell (PJV.ps1):

if($args[0] -eq "11") {
   $Env:JAVA_HOME="$ENV:JAVA11"
   $Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
} elseif($args[0] -eq "17") {
   $Env:JAVA_HOME="$ENV:JAVA17"
   $Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
} elseif($args[0] -eq "8") {
   $Env:JAVA_HOME="$ENV:JAVA8"
   $Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
}
set "Path=%JAVA_HOME%\bin;%Path%"
java -version

From command line (JV.bat):

@echo off
if "%~1" == "11" (
   set "JAVA_HOME=%JAVA11%"
   setx JAVA_HOME "%JAVA11%"
) else if "%~1" == "17" (
   set "JAVA_HOME=%JAVA17%"
   setx JAVA_HOME "%JAVA17%"
) else (
   set "JAVA_HOME=%JAVA8%"
   setx JAVA_HOME "%JAVA8%"
)
set "Path=%JAVA_HOME%\bin;%Path%"
java -version

Finally both these files are in the same folder. And this folder path has been added to my system PATH

enter image description here

Trinl answered 26/5, 2022 at 8:48 Comment(0)
C
1

If your path have less than 1024 characters can execute (Run as Administrator) this script:

@echo off 
set "JAVA5_FOLDER=C:\Java\jdk1.5.0_22"
set "JAVA6_FOLDER=C:\Java\jdk1.6.0_45"
set "JAVA7_FOLDER=C:\Java\jdk1.7.0_80"
set "JAVA8_FOLDER=C:\Java\jdk1.8.0_121"
set "JAVA9_FOLDER=C:\Java\jdk-10.0.1"
set "CLEAR_FOLDER=C:\xxxxxx"

(echo "%PATH%" & echo.) | findstr /O . | more +1 | (set /P RESULT= & call exit /B %%RESULT%%)
set /A STRLENGTH=%ERRORLEVEL%
echo path length = %STRLENGTH%
if %STRLENGTH% GTR 1024  goto byebye 

echo Old Path: %PATH%
echo =================== 
echo Choose new Java Version:
echo [5] JDK5
echo [6] JDK6 
echo [7] JDK7
echo [8] JDK8
echo [9] JDK10
echo [x] Exit

:choice 
SET /P C=[5,6,7,8,9,x]? 
for %%? in (5) do if /I "%C%"=="%%?" goto JDK_L5 
for %%? in (6) do if /I "%C%"=="%%?" goto JDK_L6
for %%? in (7) do if /I "%C%"=="%%?" goto JDK_L7 
for %%? in (8) do if /I "%C%"=="%%?" goto JDK_L8 
for %%? in (9) do if /I "%C%"=="%%?" goto JDK_L9
for %%? in (x) do if /I "%C%"=="%%?" goto byebye
goto choice 

@echo on
:JDK_L5  
set "NEW_PATH=%JAVA5_FOLDER%"
goto setPath

:JDK_L6  
@echo off 
set "NEW_PATH=%JAVA6_FOLDER%"
goto setPath

:JDK_L7  
@echo off 
set "NEW_PATH=%JAVA7_FOLDER%"
goto setPath

:JDK_L8  
@echo off 
set "NEW_PATH=%JAVA8_FOLDER%"
goto setPath

:JDK_L9  
@echo off 
set NEW_PATH = %JAVA9_FOLDER%

:setPath
Call Set "PATH=%%PATH:%JAVA5_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA6_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA7_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA8_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA9_FOLDER%=%CLEAR_FOLDER%%%"
rem echo Interim Path: %PATH%
Call Set "PATH=%%PATH:%CLEAR_FOLDER%=%NEW_PATH%%%" 

setx PATH "%PATH%" /M

call set "JAVA_HOME=%NEW_PATH%"
setx JAVA_HOME %JAVA_HOME% 

echo New Path: %PATH%
:byebye
echo
java -version
pause

If more than 1024, try to remove some unnecessary paths, or can modify this scripts with some inputs from https://superuser.com/questions/387619/overcoming-the-1024-character-limit-with-setx

Choke answered 15/5, 2018 at 9:3 Comment(0)
B
1

Load below mentioned PowerShell script at the start of the PowerShell. or generate the file using New-Item $profile -Type File -Force this will create a file here C:\Users\{user_name}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile

Now copy-paste the content given below in this file to be loaded each time the PowerShell is started

Set all the java versions you need as separate variables.

  1. Java_8_home-> Points to Java 8 Location in local
  2. Java_11_home -> Points to Java 11 Location in local
  3. Java_17_home -> Points to Java 17 Location in local
  4. Java_Home-> This points to the java version you want to use

Run in power shell to update the version to 8 update_java_version 8 $True

To update execution policy to allow script to be loaded at start of the PowerShell use below command Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Force

`

function update_java_version($version, [bool] $everywhere)
{
    switch ($version)
    {
        8 {
            $java_value = (Get-Item Env:Java_8_home).value
            $Env:Java_Home = $java_value
            refresh-path
            break
        }
        11 {
            $java_value = (Get-Item Env:Java_11_home).value
            $Env:Java_Home = $java_value
            refresh-path
            break
        }
        17 {
            $java_value = (Get-Item Env:Java_17_home).value
            $Env:Java_Home = $java_value
            refresh-path
            break
        }
        default {
            throw "No matching java version found for `$version`: $version"
        }
    }
    if ($everywhere)
    {
        [System.Environment]::SetEnvironmentVariable("Java_Home", $java_value, "User")
    }
}

function refresh-path
{
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
            ";" +
            [System.Environment]::GetEnvironmentVariable("Path", "User")
}
Bastille answered 4/1, 2022 at 8:51 Comment(0)
K
0

Run this BAT file to conveniently change the java version.

Pros:

  1. It does NOT modify the PATH system environment variable.
  2. The only thing that has to be maintained is the relational array (can be conveniently constructed as a sparse array) that holds the version number and the path at the beginning of the script.

Precondition:

The following entry %JAVA_HOME%\bin has to be appended to the PATH environment variable.

@echo off
@cls
@title Switch Java Version
setlocal EnableExtensions DisableDelayedExpansion

:: This bat file Switches the Java Version using the JAVA_HOME variable.
:: This script does NOT modify the PATH system environment variable.
:: Precondition: The following entry "%JAVA_HOME%\bin" has to be appended to the PATH environment variable.
::  Script Name: SwitchJavaVersion | Version 1 | 2021/11/04

rem Add items to vector as follows:
rem   AvailableVersions["Java Major Version Number"]="Java Absolute Path"
set AvailableVersions[8]="D:\Program Files\Java\jdk8u252-b09"
set AvailableVersions[17]="D:\Program Files\Java\jdk-17.0.1"

call :PrintJavaVersion
call :PrintAvailableVersions
call :GetJavaVersion
call :SetJavaVersion
call :ResetLocalPath
if %errorlevel% neq 0 exit /b %errorlevel%
call :PrintJavaVersion

pause
endlocal
exit /b


rem Print available versions.
:PrintAvailableVersions
    echo Available Java Versions:
    for /f "tokens=2 delims=[]" %%I in ('set AvailableVersions[') do echo ^> %%I
    exit /b

rem Get version from user input or command-line arguments.
:GetJavaVersion
    set "JavaVersion="
    if "%~1"=="" (
        set /p JavaVersion="Type the major java version number you want to switch to: "
    ) else (
        set /a JavaVersion="%~1"
    )
    exit /b


rem Update JAVA_HOME user variable with hardcoded paths.
:SetJavaVersion
    set JavaPath=
    for /f "tokens=2 delims=[]" %%I in ('set AvailableVersions[') do (
        if "%%I" == "%JavaVersion%" (
            setlocal EnableDelayedExpansion
            set JavaPath=!AvailableVersions[%%I]!
            setlocal EnableExtensions DisableDelayedExpansion
        )
    )

    if not defined JavaPath (
        echo "Specified version NOT found: Default settings applied."
        for /f "tokens=2 delims==" %%I in ('set AvailableVersions[') do (
            set JavaPath=%%I
            goto exitForJavaPath
        )
        
    )
    :exitForJavaPath

    rem remove quotes from path
    set JavaPath=%JavaPath:"=%
    set "JAVA_HOME=%JavaPath%"
    setx JAVA_HOME "%JAVA_HOME%"
    
    rem setlocal statement was run 2 times previously inside the for loop; therefore, the endlocal statement must be executed 2 times to close those nested local scopes.

    
    rem below endlocal statement will close local scope set by previous "setlocal EnableExtensions DisableDelayedExpansion" statement
    endlocal & set "JavaPath=%JavaPath%"
    rem JAVA_HOME's value rolls back due to endlocal statement so the appropriate value has to be reassigned
    set "JAVA_HOME=%JavaPath%"
    rem below endlocal statement will close local scope set by previous "setlocal EnableDelayedExpansion" statement
    endlocal & set "JavaPath=%JavaPath%"
    rem JAVA_HOME's value rolls back due to endlocal statement so the appropriate value has to be reassigned
    set "JAVA_HOME=%JavaPath%"
    
    exit /b


rem Get User and System Path variable's definition from Registry,
rem    evaluate the definitions with the new values and reset
rem    the local path variable so newly set java version
rem    is properly displayed.
:ResetLocalPath
    set "PathValue="
    for /F "skip=2 tokens=1,2,*" %%I in ('%SystemRoot%\System32\reg.exe QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /V Path') do if /I "%%I" == "Path" if not "%%~K" == "" if "%%J" == "REG_SZ" (set "PathValue=%%~K") else if "%%J" == "REG_EXPAND_SZ" call set "PathValue=%%~K"

    if not defined PathValue goto pathError

    set "UserPathValue="
    for /F "skip=2 tokens=1,2,*" %%I in ('%SystemRoot%\System32\reg.exe QUERY "HKCU\Environment" /V Path') do if /I "%%I" == "Path" if not "%%~K" == "" if "%%J" == "REG_SZ" (set "UserPathValue=%%~K") else if "%%J" == "REG_EXPAND_SZ" call set "UserPathValue=%%~K"

    if not defined UserPathValue goto pathError
    
    call set "Path=%PathValue%;%UserPathValue%"

    echo Path variable reset:
    echo PATH=%Path%  
    echo.
    exit /b


rem Display the Java version.
:PrintJavaVersion
    echo Current Java Version:
    java -version
    echo.
    exit /b


rem Error handling subroutine.
:pathError
    echo.
    echo Error while refreshing the PATH variable:
    echo PathValue=%PathValue%
    echo UserPathValue=%UserPathValue%
    pause
    exit /b 2

endlocal
exit
Knott answered 5/11, 2021 at 4:22 Comment(0)
A
0

If you use Git bash, you can create & use the aliases, to do that, first create/update profile file:

nano ~/.profile

Add your aliases on it:

alias j17='export JAVA_HOME=C:\\dev_tools\\jdk\\eclipse_temurin\\jdk-17.0.11+9;export PATH=$JAVA_HOME/bin:$PATH'

alias j8='export JAVA_HOME=C:\\dev_tools\\jdk\\eclipse_temurin\\jdk8u412-b08;export PATH=$JAVA_HOME/bin:$PATH'

PS: Use double anti-slash \\ as a separtor

The next step:

source ~/.profile

Now, you can use the aliases to switch between the java versions

enter image description here

Allow answered 18/6 at 16:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.