According to Wikipedia –

Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers “write once, run anywhere” (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.

Here in this blog I’ll explain scenarios where you might need to fiddle with multiple java versions in same machine.

With many ways to follow I’ll list two ways by which you can achieve it. I’ve learned the below methods from stack overflow a popular knowledge sharing platform.

1- Open Terminal and type the following command

 /usr/libexec/java_home -V 

With this command it will help us to identify how many java instances are present in system so that we can toggle between them –

The result would be like this –

1.8.0_05, x86_64:"Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_05.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


Now if you want to use 1.6.0_65-b14-462 version of Java type the below line in terminal –

export JAVA_HOME= /usr/libexec/java_home -v 1.6.0_65-b14-462

or use the latest version –

 export JAVA_HOME=/usr/libexec/java_home -v 1.8

Now if you’ll type in terminal

java -version

It’ll show the version you exported for use –

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)

Just add the export JAVA_HOME… line to your shell’s init file.

2- Another way of doing it is by using bash_profile –

Open .bash_profile in any of the editor available that will make switching between java versions easy:

alias j8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8`; java -version"
alias j7="export JAVA_HOME=`/usr/libexec/java_home -v 1.7`; java -version"

You can switch to Java 8 by typing the following in terminal:

$ j8
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

In this way multiple java versions can be handled and used Firmly without getting conflict when various programmes using different versions.