Use multiple JDK at the same time in OS X (Switch JAVA_HOME)

Sometime you need to switch between jdk versions according to projects requirements. It is hard to change JAVA_HOME each time for a specific project, so instead of setting up JAVA_HOME per project we can write a bash script to switch between versions.


export JAVA_HOME=$(/usr/libexec/java_home)

this is the normal JAVA_HOME export which is default set up preferred by mac OSX .


/usr/libexec/java_home -V

above command lists installed java versions which are also seen via Java Preferences menu inside the System properties of Mac.

So when we give  JAVA_HOME as $(/usr/libexec/java_home) it takes the latest version automatically. If we use small -v operator and pass the argument to this path like :


$(/usr/libexec/java_home) -v 1.7

then it tries to set up JAVA_HOME to version 1.7

So basically we can write a function  :


switchJDK(){
export JAVA_HOME=$(/usr/libexec/java_home - v $1
}

and add this function to ~/.bash_profile  or whatever you used for the PATH variables


export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

switchJDK(){
export JAVA_HOME=$(/usr/libexec/java_home - v $1
}

then reload bash_profile


$ source ~/.bash_profile

now we can try to switch between JDKs:

Screen Shot 2016-01-14 at 16.52.19