Sometimes, you may need to work on different projects that are written in different versions of Java. Therefore, it is beneficial to have the ability to quickly and easily switch between Java versions for compiling code or executing class files.
In this article, I will guide you on how to install multiple versions of Java simultaneously on a Windows system and demonstrate how to switch between them using the command line.
|Windows 10||Java 8||Java 11|
For easy management, it’s best to install all Java versions in a single directory. This enables seamless switching between versions. In this guide, I’ll demonstrate how to install and switch between multiple Java versions on Windows, all within a single directory:D:\SATAProgramFiles\Java
Setting Environment Variables in Windows
To set the necessary environment variables in Windows, follow these steps:
- Open the System Properties window by right-clicking on the “This PC” or “My Computer” icon, selecting “Properties,” and then clicking on “Advanced system settings.”
- In the System Properties window, click on the “Environment Variables” button.
- In the “System Variables” section, click on the “New” button to create a new environment variable.
- Enter “JAVA_HOME” as the variable name.
- Set the variable value to the directory path of your default Java version. For example, “C:\Program Files\Java\jdk1.8.0_281” (replace with the appropriate path for your system).
- Click “OK” to save the variable.
- Find the “Path” variable in the “System Variables” list and select it.
- Click on the “Edit” button to modify the variable.
- In the “Edit Environment Variable” window, add the following entry at the end of the variable value: “%JAVA_HOME%\bin”.
- Click “OK” to save the changes.
- Additionally, if you want to add a directory with scripts to the Path variable, such as “D:\SATAProgramFiles\Java\scripts”, you can follow the same steps as above, but this time modify the “Path” variable and append the directory path at the end.
- Save the changes and exit the Environment Variables window.
By setting the JAVA_HOME variable and adding the appropriate directories to the Path variable, you can conveniently switch between different Java versions and access the associated scripts from the command line.
Remember to save your scripts with different Java versions in the specified directory, such as “D:\SATAProgramFiles\Java\scripts\java11.bat” for Java 11.
These environment variable settings will ensure that the correct Java version is used for compilation and execution, and the scripts will be accessible from any location in the command prompt.
@echo off set JAVA_HOME=D:\SATAProgramFiles\Java\jdk-11.0.7 set Path=%JAVA_HOME%\bin;%Path% echo Java 11 is Activated
java -version java8 java11 where java echo %JAVA_HOME%