Where to define it
Ok, first of all, we have to make clear where to set JAVA_HOME
.
Simplified, you can define it in two files: either ~/.bashrc
or ~/bash_profile
. By default the former is executed for what is called "interactive non-login shells" while the latter is used for "login shells".
A "login shell" is exactly what you'd expect: a shell which is started after login via command line. An "interactive non-login shell" is a shell which is started from within a GUI for example. So, according to that, we should put our export statement into ~/.bashrc
.
Side note: While OS X's "Terminal" application reads both files mentioned, this is not the default behavior and therefor should not be treated as such. And thats why I wrote an explanation.
What do define
You need to export JAVA_HOME in the ~/.bashrc
file so that every time a shell is opened, the variable is set.
On OS X, the Java Development Kits and Runtime Environments are stored under /Library/Java/JavaVirtualMachines/
for quite a while now. Have a look there. This is how it looks at my machine:
/Library/Java/JavaVirtualMachines/
├── jdk1.7.0_45.jdk
├── jdk1.8.0_20.jdk
├── jdk1.8.0_25.jdk
└── jdk1.8.0_51.jdk
The subfolders look similar to this
jdk1.7.0_45.jdk/
└── Contents
├── Home
├── Info.plist
└── MacOS
And there we got it. So if you wanted to point to the JDK 1.7.0_45, you'd put the following statement into your .bashrc
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home"
To make sure that the correct binaries for that Java version are called, you also should add the following somewhere after the above statement:
export PATH=$JAVA_HOME/bin:$PATH