Switching between java JDKs versions on Mac OS X [Shell-2]

For some reason, you want to have more than only one JDKs on your machine. So you have made the installations and want to easily switch between them.

JDKs Inventory

On MacOS, once JDKs are installed, they are located in the /Library/Java/JavaVirtualMachines directory. 

[Terminal-2] Switch JDKs - Terminal analysis - 965*319

As you can see in this screenshot, I have the Java 7 and Java 8 versions available on my Mac. But the 1.8 is my default one.

Configuration

The solution if you want to switch from one to another is to use the /usr/libexec/java_home command which give you the absolute PATH. A good way is to use this command to define aliases.

Create aliases

In order to do that, edit your ~/.bash_profile (or your~/.zshrc if you use zsh the wonderful oh my zsh created by Robby Russel) and add the following lines:

# Languages :
# -----------
# - [Java]
alias java7_export='export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)'
alias java8_export='export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)'

Save your profile and source it with the following command

source ~/.bash_profile

Use

Now, you can use your new aliases to switch between your Java JDKs.

[Terminal-2] Switch JDKs - Test aliases - 620x415

 

Leave a Reply