Tuesday, November 25, 2014

Easily changing java versions in OSX

In OSX, they've frankly done a pretty good job of enabling multiple versions of java at the same time, but just as frankly it's somewhat obscure and inconvenient to manage multiple versions. It's not mind bogglingly difficult but for us oldsters who are lazy, I created a convenient way to switch versions inspired by (though nowhere nearly as awesome as) rvm for ruby.

  1. Download all of the versions of java you want to use from the appropriate location java 1.6, java 7, or java 8. (you need at least one to start with)
  2. Add the following lines to ~/.bash_profile
  3. jvm() {
     export JAVA_HOME=`/usr/libexec/java_home -v "$1"`
     java -version
  4. Either source .bash_profile by typing ". ~/.bash_profile" or simply close your terminal and relaunch

At this point you can change versions of java by typing:

jvm 1.6*
jvm 1.7*

Yes, there's more to it, refer to java_home for more version matching options, and it could be way more awesome, but this should be a quick help for those who just need a simple way to switch when troubleshooting/testing jvm version issues and you want to quickly change JDKs in an automated fashion. Note, this also works with fix pack and minor versions, you just need to refer to the version pattern matching of the '-v' option for java_home to know how to use it.

edit - I originally had an alias pointing to a function until a gracious commenter pointedly asked why I did it that way. Not having an answer I eliminated the alias. This shows the strength of my convictions about the "right way" to do things...


Anonymous said...

Why the alias? Why not just name th function "jvm" to begin with?

Mike Mainguy said...

Ummm, yeah, really good point, amending my post, thanks!

Michael said...

> Either source .bash_profile by typing ". ~/.bash_profile"
> or simply close your terminal and relaunch

This function doesn't set the PATH, which is all that really needs to be done (and that's presumably what's happening in ~/.bash_profile or ~/.bashrc). Note that closing/re-opening a terminal would undo the local changes in the shell made to the env var JAVA_HOME.

The main point of all of this is to put $JAVA_HOME/bin at the beginning of the PATH (i.e., PATH="$JAVA_HOME/bin:$PATH"). Removing the old/unused jvm's from the PATH being ideal but typically unnecessary.

(nb: I came here following your comment in another post; see my comment here: http://www.jayway.com/2014/01/15/how-to-switch-jdk-version-on-mac-os-x-maverick/#comment-149143 )

Macluq said...

Doesn't really work for me, on:

System Version: OS X 10.9.5 (13F34)
Kernel Version: Darwin 13.4.0

Mike Mainguy said...

@macluq - do you have an error? can I see a copy of your .bash_profile?

Anonymous said...

Thank you very much! I read a zillion post but, this one is clear, concise and WORKED!!.
I created a bash file (after installing osx Yosemite and now can easily switch between JDK 1.7 and 1.8.