I've installed a version of Java. How can we set the $JAVA_HOME environment variable correctly?
- 28,986
- 11,913
4 Answers
You can set your JAVA_HOME in /etc/profile as Petronilla Escarabajo suggests. But the preferred location for JAVA_HOME or any system variable is /etc/environment.
Open /etc/environment in any text editor like nano or gedit and add the following line:
JAVA_HOME="/usr/lib/jvm/open-jdk"
(java path could be different)
Use source to load the variables, by running this command:
source /etc/environment
Then check the variable, by running this command:
echo $JAVA_HOME
Update
Usually most linux systems source /etc/environment by default. If your system doesn't do that add the following line to ~/.bashrc (Thanks @pje)
source /etc/environment
- 72,312
- 8,755
To set JAVA_HOME environment variable, do the following:
- Launch Terminal by pressing Ctrl+Alt+T on your keyboard.
- Enter the following command:
$gksudo gedit /etc/environment - Depending on where you installed your Java, you will need to provide the full path. For this example, I installed Oracle JDK 7 in the
/usr/lib/jvm/java-7-oracledirectory.
Scroll to the end of the file and enter the following:
JAVA_HOME=/usr/lib/jvm/java-7-oracle
export JAVA_HOME - Save your file and exit gedit.
- Lastly, reload the system PATH with the following command:
$. /etc/environment
The above method will save you the hassle in having to run the commands every time you log in to your computer.
- 1,644
If you do not know the path and you only have openJDK installed, you can type
update-alternatives --config java and you should find the path. To set the variable you can write JAVA_HOME=<PATH> followed by export JAVA_HOME. Notice there's no space when declaring the variable. To check if the variable is stored you simply type echo $JAVA_HOME to verify.
- 899
This is the best option if you always want to use the latest one installed.
Nowadays (Ubuntu 23.10) you should probably have it installed through apt like:
sudo apt install default-jdk # or default-jre
In this case, you should find it at /usr/lib/jvm/default-java.
It's a symlink that points to whichever the current JVM is on the same folder.
So, just run this to add the environment as a separate file:
sudo nano /etc/environment.d/90java.conf
Add this line and save:
JAVA_HOME="/usr/lib/jvm/default-java"
Then reboot or login again, or source /etc/environment.d/90java.conf to load it on the current shell.
- 697