Selecting the java version in Mac OS

I have currently two versions of the JDK installed on my mac. I want to select which one I am going to use in a terminal session. I found out about this neat command that allows me to set the Java home path :

/usr/libexec/java_home -verbose

This will output the installed versions of the JDK. In my case this is the output

1.7.0_07, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_07.jdk/Contents/Home
1.6.0_65-b14-462, x86_64: "Java SE 6" /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
1.6.0_65-b14-462, i386: "Java SE 6" /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

To set the JAVA_HOME environment variable and use the desired JDK type something like :

export JAVA_HOME=$(/usr/libexec/java_home -v '1.6*')

Then, when we execute the java executable :

java -version

we will get the desired version of the executable

java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609)
Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)