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.

export DEV_TOOLS=/Users/allandequeiroz/dev

JAVA7=$DEV_TOOLS/java7
JAVA8=$DEV_TOOLS/java8
JAVA8=$DEV_TOOLS/java9

function j7 {
        export JAVA_HOME=$JAVA7
        export MAVEN_HOME=$DEV_TOOLS/apache-maven-2.2.1
        export PATH=$JAVA_HOME/bin:$PATH 
        export PATH=$MAVEN_HOME/bin:$PATH
}

function j8 {
        export JAVA_HOME=$JAVA8
        export MAVEN_HOME=$DEV_TOOLS/apache-maven-3.3.9
        export PATH=$JAVA_HOME/bin:$PATH 
        export PATH=$MAVEN_HOME/bin:$PATH
}

function j9 {
        export JAVA_HOME=$JAVA8
        export MAVEN_HOME=$DEV_TOOLS/apache-maven-3.3.9
        export PATH=$JAVA_HOME/bin:$PATH 
        export PATH=$MAVEN_HOME/bin:$PATH
}

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

j7

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

Moving to 8

j8

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!

Allan de Queiroz

Allan de Queiroz
London based software engineer

XServer forward from Linux text mode for Headless purposes.

Hello, this post is about XServer forward from Linux text mode, **not ssh forward, anything related to VNC** or things like that.Recently...… Continue reading