Macos – Switching between Java 7 and 8 in OS X

environment-variablesjavamacos

I have installed Java-8. Now I wanted to go back to Java-7 by default so I type in…

/usr/libexec/java_home -v 1.7.0_40 --exec java -version
/usr/libexec/java_home -v 1.7.0_40 --exec javac -version

But I still see…

java -version
java version "1.8.0-ea"
Java(TM) SE Runtime Environment (build 1.8.0-ea-b108)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b50, mixed mode)

This does work…

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home

But I would like a more permanent solution.

Anyone see what I am doing wrong?

Best Answer

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.

Related Question