How to quickly change JDK versions on Linux/MacOs

Inspired by some tutorials about how to configure JAVA_HOME on Linux/MacOs I’ll show here how to quickly change JDK versions on Linux/MacOs.

FYI: You can use this trick to swap between any kind of configuration that you need, I’ll use Java as an example just because.

The problem

Sometimes you’re working with wide versions of the same technology, that use the same environment variables but are in different places in the file system, a good example is JDK.

Some guys go back to .bashrc or .bash_profile every time and set different values to the same variables to work properly with whatever they need.

Time and patience are required and worse, is repetitive.

Solution

Defining functions that can be executed anywhere, this is part of my .bash_profile to handle Java versions.

We can define environment variables inside functions, so if I’m working now with java 9 and for some reason, I need to compile some code in Java 7, all that have to do is

Now I’m on JDK 7 and Maven 2 :'(

Moving to 8

That’s it. There are more interesting things like alias for example, where you can define guess what? Aliases to complex or long commands, but let’s see it in another post, see ya!

Leave a Reply