- JAVA_HOME directory in Linux
- 11 Answers 11
- How to Set JAVA_HOME Linux
- Prerequisites
- JDK vs. JRE
- Environment variables
- JAVA_HOME
- Setting up JAVA_HOME
- Setting JAVA_HOME globally
- Final thoughts
- About the author
- Sidratul Muntaha
- Как найти JAVA_HOME
- 2. Способы поиска JAVA_HOME для Windows «
- 3. Специфичные для macOS и Linux способы поиска JAVA_HOME
JAVA_HOME directory in Linux
Is there any linux command I could use to find out JAVA_HOME directory? I’ve tried print out the environment variables («env») but I can’t find the directory.
11 Answers 11
On Linux you can run $(dirname $(dirname $(readlink -f $(which javac))))
On Mac you can run $(dirname $(readlink $(which javac)))/java_home
I’m not sure about windows but I imagine where javac would get you pretty close
This is a great solution, but remember to use the canonical flag for readlink as Java can be set up with multiple links, so use $(dirname $(dirname $(readlink -f $(which javac)))) on Linux instead
Thanks @MatthewO’Riordan! I added the -f flag for the linux command. Note that readlink on mac is not the GNU version so I excluded -f for the mac version of the script. Mac users that have the GNU version of readlink installed via brew can use -f .
This is the best solution to find any home paths. I use it frequently for java, maven, and whatnot! Thank you!
Ah, nevermind, the intention is clearer with an echo before it: echo $(dirname $(dirname $(readlink -f $(which javac))))
Just another solution, this one’s cross platform (uses java ), and points you to the location of the jre.
java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'
Outputs all of java ‘s current settings, and finds the one called java.home .
For windows, you can go with findstr instead of grep.
java -XshowSettings:properties -version 2>&1 | findstr "java.home"
I’ve reseached a lot of ways to find JAVA_HOME and I think this is one of the best! Thanks for mentioning it!
It’s probably worth mentioning that this started working with JDK1.7 (IIRC). Before that you would have needed to call: jrunscript -e ‘java.lang.System.out.println(java.lang.System.getProperty(«java.home»));’ . In both cases, for ‘cross-platform’ aspects, it is recommendable to prepend a /usr/bin/env .
echo $JAVA_HOME will print the value if it’s set. However, if you didn’t set it manually in your startup scripts, it probably isn’t set.
If you try which java and it doesn’t find anything, Java may not be installed on your machine, or at least isn’t in your path. Depending on which Linux distribution you have and whether or not you have root access, you can go to http://www.java.com to download the version you need. Then, you can set JAVA_HOME to point to this directory. Remember, that this is just a convention and shouldn’t be used to determine if java is installed or not.
@harschware When I install Ubuntu the JAVA_HOME is not set, even with the JDK installed. Also read /usr/share/doc/openjdk-8-jre-headless/JAVA_HOME and it says the JAVA_HOME should no longer be needed (legacy).
@PeterQuiring Thanks Peter, unfortunately I don’t have easy access to that file. Perhaps there is an effort to deprecate it in Java 8, but the shear number of tools that rely on JAVA_HOME will mandate a need to continue to define the variable for many years yet.
I know this is late, but this command searches the /usr/ directory to find java for you
/usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-1.6.0-openjdk
FYI, if you are on a Mac, currently JAVA_HOME is located at
You might want to try sudo find /usr/ -name *jdk* as my path was /usr/lib/jvm/java-7-openjdk-amd64/ .
To show the value of an environment variable you use:
In case you don’t have it setted, you can add in your .bashrc file:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed «s:bin/java::»)
and it will dynamically change when you update your packages.
Unsafe sed command: what if /usr/bin/java was a symlink to /usr/bin/java-8/bin/java ? You’d get the output /usr/-8/bin/java .
Fantastic Solution! if you want to use jdk as home instead of jre just tweak readlink -f /usr/bin/java | sed «s:jre/bin/java::»
If $JAVA_HOME is defined in your environment.
$ echo $JAVA_HOME $ # I am not lucky.
You can guess it from the classes that are loaded.
$ java -showversion -verbose 2>&1 | head -1 [Opened /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/jre/lib/rt.jar]
This method ensures you find the correct jdk / jre used in case there are multiple installations.
$ strace -e open java -showversion 2>&1 | grep -m1 /jre/ open("/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/jre/bin/../lib/amd64/jli/tls/x86_64/libpthread.so.0", O_RDONLY) = -1 ENOENT (No such file or directory)
If you are not getting anything, then your environment variable JAVA_HOME has not been set. You can try using «locate java» to try and discover where your installation of Java is located.
Did you set your JAVA_HOME
- Korn and bash shells:export JAVA_HOME=jdk-install-dir
- Bourne shell:JAVA_HOME=jdk-install-dir;export JAVA_HOME
- C shell:setenv JAVA_HOME jdk-install-dir
Here’s an improvement, grabbing just the directory to stdout:
java -XshowSettings:properties -version 2>&1 \ | sed '/^[[:space:]]*java\.home/!d;s/^[[:space:]]*java\.home[[:space:]]*=[[:space:]]*//'
A bit shorter, though with three forks instead of two, is the following: : $
If one needs to export the path directly: export $(/usr/bin/env java -XshowSettings:properties -version 2>&1 | grep «java.home» | sed -e ‘s/java.home/JAVA_HOME/;s/ //g;’)
You can check from the command line by executing this command echo $JAVA_HOME . If Java is installed but the path is not set, you need to identify the path to your java installation. I prefer using sudo update-alternatives —config java which lists all installed versions with current active one marked and provides dialog to switch:
There are 3 programs which provide 'java'. Selection Command ----------------------------------------------- 1 java-11-openjdk.x86_64 (/usr/lib/jvm/java-11-openjdk-11.0.14.0.9-2.fc35.x86_64/bin/java) 2 java-17-openjdk.x86_64 (/usr/lib/jvm/java-17-openjdk-17.0.2.0.8-1.fc35.x86_64/bin/java) *+ 3 /usr/java/jdk-17.0.2/bin/java Enter to keep the current selection[+], or type selection number:
from the above list, you can select the version of java you want to be the default. To set the JAVA_HOME to option 3 for instance you can do it this way export JAVA_HOME=/usr/java/jdk-17.0.2
How to Set JAVA_HOME Linux
Java is one of the most influential and popular programming languages. Originally released by Sun Microsystems in 1995, Java is a cross-platform language that is now a part of almost every aspect of technology. You will find Java everywhere – banking, financial services, big data, stock market, mobile (Android), and more. It easily ranks among the top programming languages and is likely to remain so for at least a decade.
In this guide, we’ll showcase one of the basic and crucial steps of configuring Java on your system – setting up the JAVA_HOME environment variable in Linux.
Prerequisites
Before diving deeper, let’s quickly refresh on various concepts and keywords.
JDK vs. JRE
If you’re interested in Java, you are probably already familiar with them. JDK stands for “Java Development Kit.” It contains the necessary tools and libraries to build and run (using JRE) Java apps. If you’re interested in learning or working on a Java project, JDK is the option to choose.
JRE stands for “Java Runtime Environment.” This package contains the tools and libraries needed to run a Java application. It’s a must-have to run any Java program on the system.
Note that JDK comes bundled with JRE by default. So, you don’t have to install JRE separately if you already have JDK installed.
Environment variables
In Linux, environment variables hold various system info available to apps. The info can be about how apps run on the environment, different system behaviors, etc.
Depending on the accessibility of the variables, we can divide them into 2 categories.
- Local environment variables: These variables are set on a per-user basis. Only the specific user can use them in their sessions.
- Global environment variables: These variables are accessible by everyone on the system.
JAVA_HOME
The JAVA_HOME is an environment variable. It holds the location of the Java binaries. Many applications rely on this environment variable to locate the Java binaries and libraries.
It can be set both on a local or global basis.
Setting up JAVA_HOME
Now that we understand what JAVA_HOME is, it’s time to learn how to set its value.
First, figure out the version of Java installed. This version number is often linked to the Java binary path.
If Java was installed globally, then the installation is likely stored at the following location.
This directory contains the Java binaries and libraries. Check the content of the directory.
In my case, I have OpenJDK 11 installed on Ubuntu (more on installing the latest Java on Ubuntu). From the output, we can see entries like “default-java” and “java-1.11.0-openjdk-amd64” are symlinks of “java-11-openjdk-amd64”.
We’re going to set the value of JAVA_HOME to java-1.11.0-openjdk-amd64 (recommended).
Note that this environment variable will only last for the current shell session. Once restarted, you have to set the value once again manually. To solve this issue, most shells come with a configuration file that contains codes and commands the shell must run whenever it launches. In the case of bash, it’s called bashrc (for zsh, it’s zshrc, etc.).
Open the file in a text editor.
Now, add the following line at the end of the file. It will mark the environment variable accessible to all shell sessions and the binaries available directly from the PATH variable.
$ export JAVA_HOME =/ usr / lib / jvm / java — 1.11.0 — openjdk — amd64
$ export PATH = $PATH : $JAVA_HOME / bin
Save the file and close the editor. To take the changes into effect, reload the bashrc file.
Setting JAVA_HOME globally
The previous section demonstrates setting up JAVA_HOME on a single user account. It’s a good practice because each user may prefer different configurations. Some may even use a completely different Java version or Java flavor.
Bash comes with a global bashrc file that every shell session in the system must load, irrespective of the user. By declaring the location of JAVA_HOME there, we can make it available for all users in the system. Note that it’s not recommended and should be used only in specific situations.
Open up the global bashrc file in a text editor. Note that it requires sudo privilege to tweak this file.
Now, update the values of JAVA_HOME and PATH.
$ export JAVA_HOME =/ usr / lib / jvm / java — 1.11.0 — openjdk — amd64
$ export PATH = $PATH : $JAVA_HOME / bin
Save the file and close the editor. Reload the file into the bash shell to take the changes into effect.
Final thoughts
In this guide, we’ve explored various concepts like environment variables and demonstrated how to set JAVA_HOME as a local or global environment variable. Numerous development apps like NetBeans, Eclipse, Maven, ANT, Apache Tomcat, Android Studio, and more depend on JAVA_HOME to function properly.
Note that if the variable was set globally, then the location must be accessible to all users in the system. Otherwise, it will cause many issues, leading to severe headaches. To solve file permission conflicts, Linux comes with a built-in tool: chown. Learn more about chown and how to use it.
About the author
Sidratul Muntaha
Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.
Как найти JAVA_HOME
В этом кратком руководстве мы узнаем, как найти JAVA_HOME в Windows, Mac и Linux.
Как мы все знаем, JAVA_HOME — это переменная среды, которую мы обычно используем для поиска исполняемых файлов Java, таких как java и javac .
2. Способы поиска JAVA_HOME для Windows «
Если мы используем Windows в качестве операционной системы, сначала нам нужно открыть нашу командную строку ( cmd ) и ввести:
Если JAVA_HOME определен в нашей среде, то приведенная выше команда распечатает его.
Или, чтобы показать местоположение исполняемого файла Java , мы можем попробовать:
3. Специфичные для macOS и Linux способы поиска JAVA_HOME
Если мы используем macOS или Linux, мы можем открыть наш терминал и ввести:
Если JAVA_HOME определен в нашей среде, то приведенная выше команда распечатает его.
Или мы могли бы попробовать:
Это, вероятно, просто показывает нам /usr/bin/java, что на самом деле не очень полезно, поскольку это символическая ссылка. Чтобы разгадать это, мы будем использовать dirname и readlink.
dirname $(dirname $(readlink -f $(which javac)))