How to Switch Between Multiple Java Versions?

While working with Java applications on Linux, the developers need to keep multiple versions of Java. The project supported on one version may not work properly on the other versions. So, switching between versions will be a frequent practice in such a case. 

Keeping its importance in view, this post offers possible methods to switch between different Java versions. 

Switch Between Multiple Java Versions

The user can easily switch between multiple versions of Java in Linux. Let’s check the current version of Java in the terminal:

$ java -version

The current Java version is 18.0.2.

To switch to the different versions of Java, take a quick look at the 2 steps procedure.

Step 1: List Java Versions

First, list down the available versions of Java in Linux and choose the version to switch. To do so, run the below-given command:

$ update-java-alternatives --list

There are 3 versions of Java (1.18.0, 1.19.0, and 1.8.0). And the third column represents the location path of each Java version.

Step 2: Set Java Version

Once the user selects the Java version, set it by entering its location path in the following command:

$ sudo update-java-alternatives --set <Path>

To switch to Java version 1.19.0 ( according to the to step 1), the following command is considered:

$ sudo update-java-alternatives --set /usr/lib/jvm/java-1.19.0-openjdk-amd64

The Java version is set.

Verify the change

To verify the change, check the current version of Java using the command:

$ java -version

The current Java version is 19.0.2.

Alternative Approach: Determine the Symlink and Switch Java Versions

The “update-alternative” facilitates the user to update the symbolic link of the “java” command which ultimately switches the user to the updated version of Java. 

If the user installed multiple versions of Java in Linux, run the following command, and enter the selection number as shown:

$ sudo update-alternatives --config java

In the above output, the current Java version is switched to “java-18”.

Verify the Change

Let’s verify the Java version by running the following command:

$ java -version

The current Java version is 18.0.2.

Conclusion

To switch between multiple versions of Java, list the available versions and switch between them using the “sudo update-java-alternatives –set <Path>” command. Alternatively, the user can also switch to the Java version by updating the symbolic link of the Java command using the “sudo update-alternatives –config java” command.

This write-up has demonstrated the procedure to switch between multiple versions of Java in Linux.