17

I have searched several ways to change JDK version on mac.

$/usr/libexec/java_home

And I got

/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home

I tried

$export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home

also tried

/usr/libexec/java_home 1.8.0_31 --exec javac -version

then I run

$echo $JAVA_HOME

/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home

then I re-check java -version

$java -version
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)

How I can really change java -version on my mac.

Michael Gao
  • 195
  • 1
  • 1
  • 8
  • Now I know why I always failed to change JDK version. Previously I have been added java 1.7 path in my ~/.bash_profile and include in PATH. Now I remove that line and I could change now. – Michael Gao Mar 01 '15 at 09:19

2 Answers2

46

To set Java to 1.8 for your shell environment, put this in your ~/.bash_profile:

export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
andrus_a
  • 2,528
  • 1
  • 16
  • 10
  • 1
    Hi. I did but when I restart terminal and re run java -version. It still shows 1.7 – Michael Gao Mar 01 '15 at 09:07
  • 2
    The advice is valid. Like you said in your other comment, other things in your .bash_profile interfered – andrus_a Mar 02 '15 at 06:41
  • 1
    I had the same problem, i had to close all the terminal open windows. Then it worked in my case i had to restart intellij, and restart iterm to work. Maybe they had some cache built in. – cabaji99 Nov 29 '17 at 19:04
  • I tried to uninstall java 9, what a headache on mac, and this solution appears : perfect – Laurent Russier Dec 27 '17 at 16:50
  • 1
    the latest version of mac defaults to zsh instead of bash, so in that case you might need to do the equivalent solution mentioned here but in ~/.zshenv instead of in ~/bash_profile – Andrew Norman May 14 '21 at 23:20
9
Solution without 3rd party tools:

leave all JDKs at their default location, under /Library/Java/JavaVirtualMachines. The system will pick the highest version by default. To exclude a JDK from being picked by default, rename its Contents/Info.plist to Info.plist.disabled. That JDK can still be used when $JAVA_HOME points to it, or explicitly referenced in a script or configuration. It will simply be ignored by system's java command. System launcher will use the JDK with highest version among those that have an Info.plist file.

When working in a shell with alternate JDK, pick your method among existing answers (jenv, or custom aliases/scripts around /usr/libexec/java_home, etc).

Dev
  • 91
  • 1
  • 3