Switching between Java 7 and 8 in OS X

Easily Switch Versions

  1. Install versions 1.6, 1.7, 1.8 in any order. Note: I believe the last one installed determines which one will be used for browser plugins, I'm not going to care about changing those below.

  2. Then, add to your ~/.bashrc or ~/.bash_profile, or where ever:

    #!/bin/bash
    export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
    
    setjdk() {
       export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    }
    
  3. Verify the change via java -version

    $ java -version
    java version "1.7.0_51"
    Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
    Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
    
    $ setjdk 1.6
    $ java -version
    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)
    
    $ setjdk 1.8
    $ java -version
    java version "1.8.0"
    Java(TM) SE Runtime Environment (build 1.8.0-b132)
    Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
    

Obviously the change is only for the duration of the shell. But you can see where you can set it globally now.


You may use jEnv (http://www.jenv.be/), which is "a command line tool to help you forget how to set the JAVA_HOME environment variable to switch between different versions of the JDK" (taken from the project's homepage).

If you're familiar with Ruby, JEnv is like using RVM or rbenv. It helps you handle several different JDKs installed on your machine without having to write your own script to switch from one JDK to another. You may change the current java version based for example on the current directory or based on a configuration file.


You can't switch between Java-versions. In the Documentation you see:

Only one JRE can be installed at a time. The system will not install a JRE that has a lower version than the current version. If you wish to install a lower version of the JRE, first uninstall the current version.

If you want to go back to an older version, you have to uninstall Java 8.