Last Updated: February 25, 2016
· dawogfather

Awesome Script for Changing Java Versions

I noticed this post
and decided that I should put up the way that I like to change my java versions.

I originally took part of this from stack overflow somewhere but have tweaked it a little to work better.

Basically I just add the following snippets to my Mac OSX ~/.profile file.


alias java_ls='/usr/libexec/java_home -V 2>&1 | grep -E "\d.\d.\d_\d\d" | cut -d , -f 1 | colrm 1 4 | grep -v Home'

function java_use() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    export PATH=$JAVA_HOME/bin:$PATH
    java -version

and then reloaded my profile by running source ~/.profile in terminal

So how do i use it?

Well just execute
at the terminal and you will get a full listing of the available installed java_home's on your machine, like this ...

tom@Toms-iMac:~/dev$ java_ls

But how do I then change my current java version?
Well just simply execute

java_use java_version

For example if you wanted to switch to use java jdk 1.6 you would simply write

java_use 1.6

or if you wanted to switch to java jdk 1.7.0_21 you would simply write

java_use 1.7.0_21.

You could also have used just java_use 1.7 if you don't mind it picking up the most recent patch revision of java 1.7 you have installed.

Running this command will also output the java -version at the end so you know which jdk you're working with, like this ...

tom@Toms-iMac:~/dev$ java_use 1.7
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)

So how does it work?

There is a java_home executable which allows you to list the available/installed java home directories and show/set the current java_home. The alias does some nice massaging of it's output to make it look better in the results. It also can take a parameter to allows you to set that as your java home. Basically it's awesome and it works.

Why is this better than other solutions?

You don't need to keep updating this script every single time you install a new version/patch/revision of the jdk.