JDK 8 and C:\ProgramData\Oracle\Java\javapath

Oracle is using a new way to set environment variable for JDK 8 on Windows. Recently I downloaded JDK 8 and install it but couldn't go back to JDK 7 by changing the PATH environment variable. And I always get 1.8 when running java -version. Even there is no JDK 8 bin directory set in PATH environment variable.

I just can't figure out how it finds the right java.exe, I looked up all over the places, the PATH variable, JAVA_HOME and Windows system settings - Advanced - Environment Variable. None of them contains directory point to JDK 8 bin directory.

Finally I found this entry in PATH environment variable and it's the first entry.

 
 C:\ProgramData\Oracle\Java\javapath
 

It contains three symlink files point to java.exe, javaw.exe and javaw.exe. It's the first entry in system PATH variable thus has the highest priority. I must say it's not a very good way to setup java bin path environment. And it makes switching between different JDK versions harder.

Why? First, it uses symlink which is very linuxish, many Windows users don't know how to deal with symlink, I bet it's true for many *inux users too, I guess Oracle wants to be more cross-platformatic but this is not the right direction. Second, it breaks the convention and compatiblity that users all get used to.

How to switch JDK version in cmd more flexibly

You can either prepend your own directory to the PATH to overwrite the Oracle one, or follow the convention to append to the end of PATH variable like always did. I prefer the second one, here is how to do it.

First, delete C:\ProgramData\Oracle\Java\javapath, then prepare two bat files

jdk7.bat

 
@echo off
set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.7.0_17
set PATH=%BACKUPPATH%
set PATH=%PATH%;%JAVA_HOME%\bin
 

jdk8.bat

 
@echo off
set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.8.0_45
set PATH=%BACKUPPATH%
set PATH=%PATH%;%JAVA_HOME%\bin
 

The BACKUPPATH stores the old PATH environment variable, because we need to append different JDK bin directory to end of it. We should backup the original PATH variable to BACKUPPATH when starting cmd window, you can create a shortcut link to cmd.exe and right click it, paste the following code to the target field

 
C:\Windows\System32\cmd.exe /k c:\bin\startup.bat
 

When you open cmd through this shortcut link, the startup.bat will be executed, you can add the following code to startup file

 
set BACKUPPATH=%PATH%
 

We will use this variable to restore PATH variable, and append JDK bin directory to the end.

Now you don't have to worry about using different JDK in same system, when you need JDK 8 which is needed for many newer version of packages, for example Lucene 6.0.0 which was built with JDK 8, just execute jdk8.bat, and for the legacy systems, execute jdk7.bat, it will compatible with most of them.

See also