javawindowscmdenvironment-variables

Switching between different JDK versions in Windows


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...


Solution

  • 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 session, 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.