Saturday, January 03, 2015

How to manage multiple JDK versions in Yosemite

See all installed java versions,  (Please note the capital V, simple v will be used later on for different purpose)
 /usr/libexec/java_home -V  
 Matching Java Virtual Machines (4):  
   1.8.0_25, x86_64:  "Java SE 8"  /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home  
   1.7.0_71, x86_64:  "Java SE 7"  /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home  
   1.6.0_65-b14-466.1, x86_64:  "Java SE 6"  /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home  
   1.6.0_65-b14-466.1, i386:  "Java SE 6"  /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home  
Now you know whats available. All you need to do now is change your ~/.bash_profile to set JAVA_HOME. Before we do so, lets see how we can use /usr/libexec/java_home tool to retrieve JAVA_HOME paths of each versions.

Following command gives JAVA_HOME path of a given java version installed.
 /usr/libexec/java_home -v  
  asanga@localhost:$ /usr/libexec/java_home -v 1.8  
  asanga@localhost:$ /usr/libexec/java_home -v 1.7  
Now, lets add that trick to our ~/.bash_profile.
 export JAVA_HOME=`/usr/libexec/java_home -v 1.8`  
 #export JAVA_HOME=`/usr/libexec/java_home -v 1.7`  
 #export JAVA_HOME=`/usr/libexec/java_home -v 1.6`  
Now you can uncomment the version you need when you need.

1 comment:

Earl Lewis said...

Rather than adding commented lines to your .bash_profile you can create aliases for each of these export statements, like this:
alias java6='export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home'
alias java7='export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_67.jdk/Contents/Home'
alias java8='export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home'

Then, when you need to change JDK you just type your alias name (e.g. java7) and voila, you've changed java versions without any clunky file editing and sourcing the file or restarting your shell.