How to find my current JAVA_HOME in ubuntu? I have to set java_home path when installing maven.
asked May 3, 2014 at 6:20
To display JAVA_HOME
variable path, type in terminal:
echo $JAVA_HOME
If nothing appears then set it with this:
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
This will differ according to your JDK type and version.
For displaying it again, follow the first command.
Follow JREs from different vendors on the same system, for using different JDK’s or switch between JDK’s.
Eliah Kagan
116k54 gold badges313 silver badges488 bronze badges
answered May 3, 2014 at 6:24
9
If you have JDK 1.6 (corresponding to Java 6) or a newer version installed, you should have a program named jrunscript
in your PATH
. You can use this to find the corresponding JAVA_HOME
. Example:
$ jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));'
/opt/local/jdk1.7.0_76/jre
You could set the environment variable like this:
$ export JAVA_HOME="$(jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));')"
Note that the JRE doesn’t include jrunscript
, so this will only work if you install the JDK, not just the JRE.
answered Aug 6, 2015 at 22:01
rob mayoffrob mayoff
5114 silver badges5 bronze badges
1
Another portable options is to extract the absolute path of the JRE from java
:
export JAVA_HOME=`type -p java|xargs readlink -f|xargs dirname|xargs dirname`
The absolute java
path is passed to dirname
twice to remove /bin/java
from the end. Complete extraction of the directory goes as follows:
$ type -p java
/usr/bin/java
$ readlink -f /usr/bin/java
/usr/lib/jvm/java-8-oracle/bin/java
$ dirname /usr/lib/jvm/java-8-oracle/bin/java
/usr/lib/jvm/java-8-oracle/bin/
$ dirname /usr/lib/jvm/java-8-oracle/bin/
/usr/lib/jvm/java-8-oracle/
answered Feb 2, 2016 at 12:31
rzymekrzymek
4444 silver badges5 bronze badges
4
To take into account the update-alternatives mechanism:
$ update-alternatives --query java | grep 'Value: ' | grep -o '/.*/jre'
You could set the environment variable like this:
$ export JAVA_HOME="$(update-alternatives --query java | grep 'Value: ' | grep -o '/.*/jre')"
answered Sep 20, 2015 at 20:12
FranciscoFrancisco
811 silver badge2 bronze badges
1
Just run a command
sudo update-alternatives --config java
It will give something like
Es gibt nur eine Alternative in Link-Gruppe java (die /usr/bin/java bereitstellt): /usr/lib/jvm/java-8-oracle/jre/bin/java
From this you have /usr/lib/jvm/java-8-oracle/ as java home. You may now export it to JAVA_HOME variable
export JAVA_HOME=/usr/lib/jvm/java-8-oracle/
Now echo $JAVA_HOME show it
answered Jan 5, 2016 at 21:24
I use this in Ubuntu LTS (14.04 / 16.04):
[ -L /etc/alternatives/java ] &&
export JAVA_HOME="$(readlink -f /etc/alternatives/java | sed -e 's//jre/bin/java$//')"
answered Apr 20, 2018 at 9:06
For Java 9 and later:
This answer https://askubuntu.com/a/657468/963 uses the enclosed Nashorn JavaScript engine Nashorn to print out the java.home
system property. Nashorn is being deprecated so an alternative is to use jshell
introduced in Java 9.
echo 'System.out.println(java.lang.System.getProperty("java.home"));' | jshell -
which on my Ubuntu 18.10 system prints out:
/usr/lib/jvm/java-11-openjdk-amd64
answered Nov 11, 2018 at 23:49
to get JAVA_HOME
:
update-alternatives --query java | grep 'Value: ' | sed 's/Value: (.*)/bin/java/1/'
## e.g. returns </opt/Oracle_Java/jre1.8.0_202>
## if </etc/alternatives/java> points to
## </opt/Oracle_Java/jre1.8.0_202/bin/java>
to set JAVA_HOME
:
export JAVA_HOME="$(update-alternatives --query java | grep 'Value: ' | sed 's/Value: (.*)/bin/java/1/')"
answered Jul 29, 2020 at 19:57
2
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.
willome
3,05219 silver badges32 bronze badges
asked Jul 13, 2009 at 1:21
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
answered Dec 18, 2013 at 8:52
8
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"
Kıvılcım
3913 silver badges8 bronze badges
answered Mar 9, 2017 at 21:45
Parth MehrotraParth Mehrotra
2,6041 gold badge22 silver badges31 bronze badges
5
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.
Liam M
5,2764 gold badges39 silver badges55 bronze badges
answered Jul 13, 2009 at 1:27
AdamCAdamC
16k7 gold badges51 silver badges67 bronze badges
7
I know this is late, but this command searches the /usr/ directory to find java for you
sudo find /usr/ -name *jdk
Results to
/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
/System/Library/Frameworks/JavaVM.framework/Home
answered Jul 31, 2012 at 15:56
cevariscevaris
5,6222 gold badges48 silver badges34 bronze badges
2
To show the value of an environment variable you use:
echo $VARIABLE
so in your case will be:
echo $JAVA_HOME
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.
answered Nov 11, 2014 at 14:23
Paulo FidalgoPaulo Fidalgo
21.6k7 gold badges99 silver badges115 bronze badges
2
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.
Or using strace
:
$ 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)
answered Apr 10, 2015 at 18:12
dnozaydnozay
23.7k5 gold badges82 silver badges104 bronze badges
On the Terminal, type:
echo «$JAVA_HOME»
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.
answered Jul 13, 2009 at 1:28
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
answered Jul 13, 2009 at 1:28
Nizar GriraNizar Grira
7332 gold badges7 silver badges21 bronze badges
0
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:]]*//'
answered Apr 23, 2017 at 3:22
2
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
answered Feb 6, 2022 at 20:13
Download Article
The easiest ways to set the JAVA_HOME environment variable on any computer
Download Article
- Windows
- macOS
- Linux
- Video
- Tips
|
|
|
|
Are you seeing Java errors like «JAVA_HOME is not defined correctly?» or «JAVA_HOME is set to an invalid directory?» If you’ve recently installed the Java Development Kit (JDK) or the Java Runtime Environment (JRE), you’ll need to set your JAVA_HOME variables and configure the path so applications know where to find Java. This wikiHow article will show you the easiest ways to change or set the Java home path on Windows, macOS, and Linux.
Things You Should Know
- Before you can set JAVA_HOME, you’ll need the full path to your JDK or JRE installation.
- Once you set the JAVA_HOME environment variable, you can run the command
echo $JAVA_HOME
to see the new path. - To set the Java home and path on Linux or macOS permanently (even after a reboot), add the environment variables to your .bashrc or .zshrc file.
-
1
Find your Java installation directory. Assuming that you didn’t change the path for the JDK or JRE during installation is not changed, it should be in a directory under C:Program FilesJava. There are a few ways to find the full path:
- Open File Explorer, click This PC in the left panel, then navigate to C:Program FilesJava. The directory you’re looking for should have the name of the JDK version, such as C:Program FilesJavajdk-19.
- If you installed the JRE instead of the JDK, you’ll have something like C:Program FilesJavajre1.8.0_351 instead.
- You can also open the command prompt and run the command wmic product where "Name like '%%Java%%'" get installlocation,Name. This will tell you the full path of the JDK, even if you haven’t yet set JAVA_HOME.
-
2
Open your Advanced System Settings. Here’s how:
- Press the Windows key on your keyboard and type advanced system.
- Click View advanced system settings in the search results.
Advertisement
-
3
Click the Environment Variables button. You’ll see it at the bottom-right corner of the System Properties window.
-
4
Click the New… button under «User variables.» You’ll have two sections on this window—»User variables» and «System variables.» You’ll want to make sure you’re clicking New under the first box (User variables).
- If you have multiple installations of the JDK and want to change JAVA_HOME to your new installation, select the current JAVA_HOME user variable and click Edit… instead.
-
5
Type JAVA_HOME as the «Variable name.»
- If you’re editing the current JAVA_HOME path, you’ll already have JAVA_HOME here. So, you can skip this step.
-
6
Enter the full path to your JDK or JRE installation. For example, if the path is C:Program FilesJavajdk-19, enter that full path into the «Variable value» field.[1]
- If you’re adding a second path to JAVA_HOME, just type a semicolon (;) after the first path, then enter the second path.
- If you’re replacing an old JAVA_HOME path, just delete the current path and enter the new one.
-
7
Click OK. This takes you back to the Environment Variables window.
-
8
Select the Path user variable and click Edit. You should already have a variable in the «User variables» section called «Path.» To make sure you can run the Java binaries, you’ll need to edit your path to add the location of the JDK bin directory.
- If you want other users on this PC to be able to access Java binaries from the command line, repeat this step for the «Path» variable under «System variables» as well.
-
9
Append the path to your Java /bin directory to the end of the path. You’ll already have at least one directory in your path, which needs to stay in place. Here’s how to add the Java bin directory:
- Click the New button at the top.
- Enter the full path to the JRE or JDK with bin at the end. For example, C:Program FilesJavajdk-19bin or C:Program FilesJavajre1.8.0_351bin.
- Click OK.
-
10
Click OK on all subsequent windows. This updates your JAVA_HOME variable and adds the Java binaries to your path.
- You won’t need to restart your computer for the changes to take effect, but you will need to relaunch any apps that were trying to access Java.
- Open a new command prompt window and run the command echo %JAVA_HOME% to display the new path to JAVA_HOME.
- Make sure this is a new command prompt window. If you still have the same window open, the command will fail because it doesn’t have the new environment variables.
Advertisement
-
1
Open a Terminal window. To open Terminal, search for Terminal in Spotlight. Or, you can open Finder, click the Go menu, select Utilities, and choose the Terminal app.
-
2
Type /usr/libexec/java_home and press ⏎ Return. This handy utility that comes preinstalled on macOS will tell you the full path to your Java installation, which you’ll need to set JAVA_HOME.
- If you have more than one Java installation and want to see the paths to all of them, use /usr/libexec/java_home -V instead.
-
3
Copy the path and paste it somewhere handy. Highlight the path to the Java installation you want to use as JAVA_HOME, press Cmd + V to copy it, then paste it into a sticky note or text file.
-
4
Open your .zshrc file in a text editor. As long as you’re using macOS Catalina or later, you’ll be using the zsh shell by default, which means you’ll add JAVA_HOME and the path to your .zshrc file.[2]
If you’re using an earlier version of macOS (or prefer the bash shell), replace .zshrc with .bashrc in these commands instead. Here’s the easiest way to open the file:- Type cd ~ and press Return.
- Type open .zshrc and press Return. This should open the file in a text editor.
- If the file is not found, type echo > .zshrc and press Return. Then, run open .zshrc again.
-
5
Add these lines to the bottom of the file. Adding these lines ensures that JAVA_HOME will be set correctly even after you log off or open another window. If the file has existing contents, just scroll down past them to enter the following text on individual lines:
-
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-17.0.1.jdk/Contents/Home
- Replace
/Library/Java/JavaVirtualMachines/jdk-17.0.1.jdk/Contents/Home
with the full path to the /Contents/Home directory of your Java installation if it’s different.
- Replace
export PATH=$JAVA_HOME/bin:$PATH
- Save the file and exit the text editor when you’re finished.
-
-
6
Type source .zshrc and press ⏎ Return. Once you’ve edited your profile, this command ensures that your environment variables will be updated for the current terminal window (and any other windows you open from now on).
-
7
Type echo $JAVA_HOME and press ⏎ Return to confirm JAVA_HOME. You should now see the full path to JAVA_HOME.
- If you had any other windows open that were attempting to find Java binaries, close and reopen them.
- Shopping for PC accessories or office supplies? Check out our coupon site for Staples discounts or our coupon site for Office Depot.
Advertisement
-
1
Open a terminal window. If you’re logged in to your desktop environment, you can press Ctrl + Alt + T to launch a terminal window.
- This method will work in just about any version of Linux, including Ubuntu and Redhat.
-
2
Find the location of your Java installation. One way you might find the Java install location is to run the which javac command, but this will only give you a symbolic link. Instead, run this command to find the location of the executable file:
- readlink -f `which javac`
- If that doesn’t work, try running update-alternatives --list java.
- If neither of these commands works, run whereis java, which will usually result in a symbolic link like /usr/bin/java.
- Once you get the directory, find out where it links using ls -la /bin/java.
- If that points you to another directory, e.g., /etc/alternatives/java, run ls -la /etc/alternatives/java.
- At that point, you should see a much longer directory, which is actually the home to the Java binaries. For example, usr/lib/jvm/java-11-openjdk-arm64/bin/java. This is the directory you want.
-
3
Set the JAVA_HOME path. Now that you have the location of Java, you can add the path to your .bashrc file (if you’re using the bash shell), .zshrc (for the zsh shell), or the equivalent for your shell.[3]
Run both of the following commands, replacing the path with the path to your JDK or JRE installation, and «bashrc» with your shell’s login script:echo "export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-arm64" >> ~/.bashrc
echo "export PATH=$PATH:$JAVA_HOME/bin" >> ~/.bashrc
-
4
Type source .bashrc to apply the changes to the current terminal window. Though you’ve already set the home for Java and added the path to its binaries permanently, the changes won’t take effect in your current terminal window until you run this command.
- At this point, you can run echo $JAVA_HOME to see the location of Java on your system.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Video
-
In Linux, you can set JAVA__HOME for all users by editing the global .bashrc, which is located at /etc/bash.bashrc. Just use echo and replace ~/.bashrc with /etc/bash.bashrc.
-
On both Linux and macOS, you can set the Java home in your .bash_profile or .zprofile if you prefer.
Thanks for submitting a tip for review!
Advertisement
About This Article
Thanks to all authors for creating a page that has been read 313,089 times.
Is this article up to date?
Во многих статьях в интернете, документации к инструментам для разработки на Java и в книгах зачастую упоминается JAVA_HOME. Что же такое JAVA_HOME?
JAVA_HOME это переменная окружения, указывающая на директорию с установленным JDK (Java Development Kit, комплект разработчика Java). JAVA_HOME это соглашение, используемое во многих программах из экосистемы Java.
Какие программы используют JAVA_HOME
- Intellij IDEA, Eclipse, NetBeans
- Apache Maven, Apache Ant, Gradle
- Apache Tomcat
- Jenkins
Некоторые игры, написанные на Java (например, Minecraft), тоже могут требовать установленной переменной JAVA_HOME.
Ошибки, связанные с JAVA_HOME
Если переменная окружения JAVA_HOME не определена, некоторые программы могут выдавать следующие ошибки:
- Переменная среды java_home не определена
- Cannot determine a valid Java Home
- JAVA_HOME is set to an invalid directory
- JAVA_HOME is not defined correctly
- JAVA_HOME environment variable is not set
- JAVA_HOME command not found
- JAVA_HOME not found in your environment
- JAVA_HOME does not point to the JDK
При появлении таких ошибок просто установите переменную JAVA_HOME
Как установить переменную окружения JAVA_HOME в Windows
Сперва вам нужно установить JDK или JRE.
- Установите JDK, если вы занимаетесь разработкой программ на Java
- Установите JRE, если вам нужно только запустить прикладную программу на Java
После установки JDK либо JRE запишите путь установки, он понадобится.
Теперь щёлкните правой кнопкой на «Мой компьютер» → «Свойства» → «Дополнительные параметры системы» → «Переменные среды…». В разделе «Системные переменные» нажмите кнопку «Создать…» и укажите следующие данные:
Имя переменной | JAVA_HOME |
Значение переменной | Путь к директории JDK / JRE, например: C:Javajdk-11.0.6 |
Сохраните изменения, кликнув «OK». Теперь выберите в списке переменную окружения Path и нажмите «Изменить…». В конце списка добавьте строчку со значением «%JAVA_HOME%bin«
Для проверки откройте консоль (Win+R, cmd) и укажите последовательно укажите две команды:
echo %JAVA_HOME%
java --version
Если вы правильно установили JDK/JRE и правильно установили переменные окружения, вы увидите вывод наподобие этого:
Это будет служить результатом того, что переменная JAVA_HOME установлена правильно и Java работает из командной строки.
Резюме
В данной статье мы рассказали вам, что являет собой переменная окружения JAVA_HOME, где она используется и как её корректно указать.
You didn’t specify a shell. So, I will assume bash
. The next issue is: did you set it for your user only or system-wide? If you set it for your user only, then run:
grep JAVA_HOME ~/.bash_profile ~/.bash_login ~/.profile ~/.bashrc
If you set it system-wide, then it may vary with distribution but try:
grep JAVA_HOME /etc/environment /etc/bash.bashrc /etc/profile.d/* /etc/profile
If the above give no answer, you can cast a wider net:
grep -r JAVA_HOME /etc
grep -r JAVA_HOME ~/
See also the suggestions in How to determine where an environment variable came from.