How to Change JDK Version From the Command Line

Posted by: Bruce Snyder on June 4, 2012

Today I was trying to figure out how to quickly change the JAVA_HOME environment variable from the terminal using the /usr/libexec/java_home command-line utility. I looked at /usr/libexec/java_home --help but didn't pay close attention to the usages because I was in on the phone. As my friend Martijn Dashorts pointed out, there's a manpage for this utility. I am embarrassed to admit that I didn't even think to check for a manpage! My idiot moment for the day, I guess. Here are the two aliases I created:

alias setjdk16='export JAVA_HOME=$(/usr/libexec/java_home -v 1.6*)'
alias setjdk17='export JAVA_HOME=$(/usr/libexec/java_home -v 1.7*)'
Put these aliases in your ~/.bash_profile or ~/.profile, reload the profile and you're ready to go. BTW, if you haven't switched from iTerm to iTerm2 yet, you should do it now ;-).
Bruce Snyder

About Bruce Snyder

Bruce Snyder has a unique skill set with a deep background in software architecture and engineering and the ability to liaise with the business side. With nearly 20 years of professional experience in enterprise and open source software, Bruce has a passion for creative problem solving, a strong work ethic and the ability to bridge the gap between business leaders and software development teams.

Bruce is a member of the Apache Software Foundation and has worked on several Apache projects. He has also authored books on Apache ActiveMQ, the Spring Framework, Apache Maven and Apache Geronimo, spoken at numerous software conferences and has helped to build communities around open source software.