Friday, March 28, 2014

Switch Java Version in Mac OS - Java 1.7.0_51

Why after installing a newer version of Java, it doesn't reflect immediately on your profile to use the right version?

Anyway, I have a simple solution on how to switch java in Mac OS. My Mac have different version of Java and I want to switch it anytime I want depends on the project that I'm working. Let's do it in 4 simple steps:


Step 1:(Check what is your current java version)
Enter the command:
   java -version
Output:
  java version "1.7.0_25"
  Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
  Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)

Step 2: (Display all the installed Java from your Mac OS)
Enter the command:
  /usr/libexec/java_home -V
Output:
Matching Java Virtual Machines (5):
    1.8.0, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home
    1.7.0_51, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home
    1.7.0_25, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_25.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

Step 3: (I will use the Java 1.7.0_51)
Enter the command:
  export JAVA_HOME=$(/usr/libexec/java_home -v 1.7.0_51)

Step 4:(Check what is your current java version after you execute the Step 3)
Enter the command:
   java -version
Output:
  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)


Step 5:(Update your bash_profile)
Enter the command:
 sudo nano ~/.bash_profile
Add the following line or update the export JAVA_HOME line and the save it (CTRL X):
  export JAVA_HOME=$(/usr/libexec/java_home -v 1.7.0_51)



2 comments:

Anonymous said...

It's a good timing. I've installed JDK 7 update 51 and when I type java -version, it's still showing JDK 6. Anyway, this post really save a lot of time. It's a straightforward. I like it simple and precise. Hope to read more like this from your blogs. Keep up the simplicity.

i360 said...

I forgot to mention that you need to add or update it into your bash_profile:

sudo nano ~/.bash_profile

then update the line with export JAVA_HOME or if it doesn't exist, just add the following line then save it:

export JAVA_HOME=$(/usr/libexec/java_home -v 1.7.0_51)

To save from Nano editor: CTRL + X