Во многих статьях в интернете, документации к инструментам для разработки на 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:\Java\jdk-11.0.6 |
Сохраните изменения, кликнув «OK». Теперь выберите в списке переменную окружения Path и нажмите «Изменить…». В конце списка добавьте строчку со значением «%JAVA_HOME%\bin«
Для проверки откройте консоль (Win+R, cmd) и укажите последовательно укажите две команды:
echo %JAVA_HOME%
java --version
Если вы правильно установили JDK/JRE и правильно установили переменные окружения, вы увидите вывод наподобие этого:
Это будет служить результатом того, что переменная JAVA_HOME установлена правильно и Java работает из командной строки.
Резюме
В данной статье мы рассказали вам, что являет собой переменная окружения JAVA_HOME, где она используется и как её корректно указать.
I need to know where JDK is located on my machine.
On running Java -version
in cmd, it shows the version as ‘1.6.xx’.
To find the location of this SDK on my machine I tried using echo %JAVA_HOME%
but it is only showing ‘JAVA_HOME’ (as there is no ‘JAVA_PATH’ var set in my environment variables).
asked Jan 13, 2011 at 14:26
3
If you are using Linux/Unix/Mac OS X:
Try this:
$ which java
Should output the exact location.
After that, you can set JAVA_HOME
environment variable yourself.
In my computer (Mac OS X — Snow Leopard):
$ which java
/usr/bin/java
$ ls -l /usr/bin/java
lrwxr-xr-x 1 root wheel 74 Nov 7 07:59 /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
If you are using Windows:
c:\> for %i in (java.exe) do @echo. %~$PATH:i
answered Jan 13, 2011 at 14:28
Pablo Santa CruzPablo Santa Cruz
177k32 gold badges241 silver badges293 bronze badges
8
Windows > Start > cmd >
C:> for %i in (javac.exe) do @echo. %~$PATH:i
If you have a JDK installed, the Path is displayed,
for example: C:\Program Files\Java\jdk1.6.0_30\bin\javac.exe
answered May 9, 2012 at 16:29
grokstergrokster
5,9591 gold badge36 silver badges22 bronze badges
5
In Windows at the command prompt
where javac
answered Jul 25, 2013 at 12:02
NanoBennettNanoBennett
1,8001 gold badge13 silver badges13 bronze badges
5
Command line:
Run where java
on Command Prompt.
GUI:
On Windows 10 you can find out the path by going to Control Panel > Programs > Java. In the panel that shows up, you can find the path as demonstrated in the screenshot below. In the Java Control Panel, go to the ‘Java’ tab and then click the ‘View’ button under the description ‘View and manage Java Runtime versions and settings for Java applications and applets.’
This should work on Windows 7 and possibly other recent versions of Windows.
answered Jul 26, 2017 at 18:46
smartexpertsmartexpert
2,6453 gold badges24 silver badges41 bronze badges
4
In windows the default is: C:\Program Files\Java\jdk1.6.0_14
(where the numbers may differ, as they’re the version).
answered Oct 24, 2013 at 21:24
Ronen RabinoviciRonen Rabinovici
8,7305 gold badges34 silver badges46 bronze badges
3
Java installer puts several files into %WinDir%\System32 folder (java.exe, javaws.exe and some others). When you type java.exe in command line or create process without full path, Windows runs these as last resort if they are missing in %PATH% folders.
You can lookup all versions of Java installed in registry. Take a look at HKLM\SOFTWARE\JavaSoft\Java Runtime Environment and HKLM\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment for 32-bit java on 64 bit Windows.
This is how java itself finds out different versions installed. And this is why both 32-bit and 64-bit version can co-exist and works fine without interfering.
answered Feb 1, 2012 at 10:48
Plain and simple on Windows platforms:
where java
answered Jan 25, 2014 at 16:33
luccaaluccaa
2973 silver badges2 bronze badges
1
Under Windows, you can use
C:>dir /b /s java.exe
to print the full path of each and every «java.exe» on your C: drive, regardless of whether they are on your PATH environment variable.
answered Nov 24, 2015 at 17:03
0
The batch script below will print out the existing default JRE. It can be easily modified to find the JDK version installed by replacing the Java Runtime Environment with Java Development Kit.
@echo off
setlocal
::- Get the Java Version
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE=CurrentVersion
reg query %KEY% /v %VALUE% 2>nul || (
echo JRE not installed
exit /b 1
)
set JRE_VERSION=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JRE_VERSION=%%b
)
echo JRE VERSION: %JRE_VERSION%
::- Get the JavaHome
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set VALUE=JavaHome
reg query %KEY% /v %VALUE% 2>nul || (
echo JavaHome not installed
exit /b 1
)
set JAVAHOME=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JAVAHOME=%%b
)
echo JavaHome: %JAVAHOME%
endlocal
answered Aug 11, 2014 at 18:21
munsinghmunsingh
3172 silver badges9 bronze badges
In a Windows command prompt, just type:
set java_home
Or, if you don’t like the command environment, you can check it from:
Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and in system variable try to find JAVA_HOME.
answered Mar 16, 2014 at 11:36
JohannJohann
27.7k39 gold badges166 silver badges280 bronze badges
1
In Windows PowerShell you can use the Get-Command
function to see where Java is installed:
Get-Command -All java
Or
gcm -All java
The -All
part makes sure to show all places it appears in the Path lookup. Below is example output.
PS C:> gcm -All java
CommandType Name Version Source
----------- ---- ------- ------
Application java.exe 8.0.202.8 C:\Program Files (x86)\Common Files\Oracle\Java\jav...
Application java.exe 8.0.131... C:\ProgramData\Oracle\Java\javapath\java.exe
answered Nov 9, 2020 at 17:32
Scott HScott H
2,6441 gold badge24 silver badges28 bronze badges
Powershell one liner:
$p='HKLM:\SOFTWARE\JavaSoft\Java Development Kit'; $v=(gp $p).CurrentVersion; (gp $p/$v).JavaHome
answered Jun 17, 2017 at 8:15
majkinetormajkinetor
8,7509 gold badges54 silver badges72 bronze badges
1
Run this program from commandline:
// File: Main.java
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("java.home"));
}
}
$ javac Main.java
$ java Main
answered Jan 13, 2011 at 14:29
PeterMmmPeterMmm
24.2k13 gold badges73 silver badges111 bronze badges
2
More on Windows… variable java.home is not always the same location as the binary that is run.
As Denis The Menace says, the installer puts Java files into Program Files, but also java.exe into System32. With nothing Java related on the path java -version can still work. However when PeterMmm’s program is run it reports the value of Program Files as java.home, this is not wrong (Java is installed there) but the actual binary being run is located in System32.
One way to hunt down the location of the java.exe binary, add the following line to PeterMmm’s code to keep the program running a while longer:
try{Thread.sleep(60000);}catch(Exception e) {}
Compile and run it, then hunt down the location of the java.exe image. E.g. in Windows 7 open the task manager, find the java.exe entry, right click and select ‘open file location’, this opens the exact location of the Java binary. In this case it would be System32.
answered Oct 24, 2012 at 10:23
Moika TurnsMoika Turns
68711 silver badges17 bronze badges
Have you tried looking at your %PATH% variable. That’s what Windows uses to find any executable.
answered Jan 13, 2011 at 14:28
sblundysblundy
60.7k22 gold badges122 silver badges123 bronze badges
1
Just execute the set
command in your command line. Then you see all the environments variables you have set.
Or if on Unix you can simplify it:
$ set | grep "JAVA_HOME"
answered Jan 13, 2011 at 14:31
1
This is OS specific. On Unix:
which java
will display the path to the executable. I don’t know of a Windows equivalent, but there you typically have the bin
folder of the JDK installation in the system PATH
:
echo %PATH%
answered Jan 13, 2011 at 14:30
Michael BorgwardtMichael Borgwardt
342k79 gold badges483 silver badges720 bronze badges
2
On macOS, run:
cd /tmp && echo 'public class Main {public static void main(String[] args) {System.out.println(System.getProperty("java.home"));}}' > Main.java && javac Main.java && java Main
On my machine, this prints:
/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
Note that running which java
does not show the JDK location, because the java
command is instead part of JavaVM.framework
, which wraps the real JDK:
$ which java
/usr/bin/java
/private/tmp
$ ls -l /usr/bin/java
lrwxr-xr-x 1 root wheel 74 14 Nov 17:37 /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
answered Jan 18, 2018 at 13:58
jameshfisherjameshfisher
34.4k31 gold badges121 silver badges167 bronze badges
None of these answers are correct for Linux if you are looking for the home that includes the subdirs such as: bin, docs, include, jre, lib, etc.
On Ubuntu for openjdk1.8.0, this is in:
/usr/lib/jvm/java-1.8.0-openjdk-amd64
and you may prefer to use that for JAVA_HOME
since you will be able to find headers if you build JNI source files. While it’s true which java
will provide the binary path, it is not the true JDK home.
answered Jan 27, 2016 at 1:33
EntangledLoopsEntangledLoops
1,9811 gold badge23 silver badges36 bronze badges
I have improved munsingh’s answer above by testing for the registry key in 64-bit and 32-bit registries, if needed:
::- Test for the registry location
SET VALUE=CurrentVersion
SET KEY_1="HKLM\SOFTWARE\JavaSoft\Java Development Kit"
SET KEY_2=HKLM\SOFTWARE\JavaSoft\JDK
SET REG_1=reg.exe
SET REG_2="C:\Windows\sysnative\reg.exe"
SET REG_3="C:\Windows\syswow64\reg.exe"
SET KEY=%KEY_1%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_2% is for 64-bit installations, using "C:\Windows\sysnative"
SET KEY=%KEY_1%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_3% is for 32-bit installations on a 64-bit system, using "C:\Windows\syswow64"
SET KEY=%KEY_1%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
:_set_value
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JDK_VERSION=%%b
)
SET KEY=%KEY%\%JDK_VERSION%
SET VALUE=JavaHome
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JAVAHOME=%%b
)
ECHO "%JAVAHOME%"
::- SETX JAVA_HOME "%JAVAHOME%"
reference for access to the 64-bit registry
answered Mar 28, 2018 at 17:51
JohnP2JohnP2
1,89919 silver badges17 bronze badges
Maybe the above methods work… I tried some and didn’t for me. What did was this :
Run this in terminal :
/usr/libexec/java_home
answered Oct 17, 2020 at 3:13
Mudit VermaMudit Verma
3742 silver badges6 bronze badges
Simple method (Windows):
Open an application using java.
press ctrl + shift + esc
Right click on OpenJDK platform binary. Click open file location.
Then it will show java/javaw.exe then go to the top where it shows the folder and click on the jdk then right copy the path, boom. (Wont work for apps using bundled jre paths/runtimes, because it will show path to the bundled runtime)
Dharman♦
31.1k25 gold badges87 silver badges138 bronze badges
answered Oct 3, 2021 at 5:59
deateaterOGdeateaterOG
1111 gold badge3 silver badges9 bronze badges
in Windows cmd:
set "JAVA_HOME"
answered Dec 25, 2014 at 17:42
HusamHusam
132 bronze badges
0
#!/bin/bash
if [[ $(which ${JAVA_HOME}/bin/java) ]]; then
exe="${JAVA_HOME}/bin/java"
elif [[ $(which java) ]]; then
exe="java"
else
echo "Java environment is not detected."
exit 1
fi
${exe} -version
For windows:
@echo off
if "%JAVA_HOME%" == "" goto nojavahome
echo Using JAVA_HOME : %JAVA_HOME%
"%JAVA_HOME%/bin/java.exe" -version
goto exit
:nojavahome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program.
goto exit
:exit
This link might help to explain how to find java executable from bash: http://srcode.org/2014/05/07/detect-java-executable/
answered May 8, 2014 at 7:01
2
Script for 32/64 bit Windows.
@echo off
setlocal enabledelayedexpansion
::- Get the Java Version
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set KEY64="HKLM\SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment"
set VALUE=CurrentVersion
reg query %KEY% /v %VALUE% 2>nul || (
set KEY=!KEY64!
reg query !KEY! /v %VALUE% 2>nul || (
echo JRE not installed
exit /b 1
)
)
set JRE_VERSION=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JRE_VERSION=%%b
)
echo JRE VERSION: %JRE_VERSION%
::- Get the JavaHome
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set KEY64="HKLM\SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set VALUE=JavaHome
reg query %KEY% /v %VALUE% 2>nul || (
set KEY=!KEY64!
reg query !KEY! /v %VALUE% 2>nul || (
echo JavaHome not installed
exit /b 1
)
)
set JAVAHOME=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JAVAHOME=%%b
)
echo JavaHome: %JAVAHOME%
endlocal
answered Mar 26, 2019 at 23:23
RudixxRudixx
1051 gold badge1 silver badge7 bronze badges
- Find Java Location Using Command
where java
- Find Java Location Using Command
set JAVA_HOME
- Find Java Location Using Command
dir /b /s java.exe
- Find Java Location Using Command
gcm -All java
in Windows PowerShell
Today, we will see how to find out where Java is located in Windows. There are multiple ways and commands to do this; we will check out various commands that return the Java location windows.
Find Java Location Using Command where java
The most commonly used command to get the current location of Java in Windows is where java
. This is a Windows command that works just like the whereis
command in Linux Operating System. The where
command is used to display the location of the executable. It usually uses a search pattern.
As shown below, when we run the command where java
in the command line of Windows, it returns the location of java.exe
.
Output:
C:\User\.jdks\openjdk-15.0.1\bin\java.exe
Find Java Location Using Command set JAVA_HOME
The next technique to get the location of Java in Windows is to use the command set JAVA_HOME
. In Windows, the path of Java or JDK is stored in the environment variables. The location is stored in the variable named PATH
, a list of directories that can be used to access certain programs like Java directly without writing the whole path.
We can set the path of Java by the command set JAVA_HOME
and then specify the path. But if the value is already set, it will return the path set to the variable JAVA_HOME
. It completes our goal as this is the directory in which Java is located.
C:\Users\Rupam Saini>set JAVA_HOME
Output:
JAVA_HOME=C:\Users\Rupam Saini\.jdks\openjdk-15.0.1
Find Java Location Using Command dir /b /s java.exe
The dir
command shows all the folders and sub-folders in the current location. We can use this command to get the locations of Java as there might be more than one executable of Java in a single Windows machine as some programs use their own Java environment.
We use the dir
command with three parameters, first is /b
that displays only the directory path without any extra details. In contrast, the /s
parameter lists every occurrence of the specified file in the current directory and subdirectories, and at last, the execute name that is java.exe
.
C:\User>dir /b /s java.exe
Output:
C:\User\.jdks\openjdk-15.0.1\bin\java.exe
C:\User\AppData\Local\JetBrains\IntelliJ IDEA Community Edition 2020.3\jbr\bin\java.exe
Find Java Location Using Command gcm -All java
in Windows PowerShell
In all the examples in this tutorial, we use the traditional command-line,, but this method requires the Windows PowerShell, a command-line but with advanced capabilities. In PowerShell, we use the gcm
command that is short for get-command
. It returns all the commands in the machine.
We use gcm
with two parameters; the first is -All
that shows all the instances of the command in the current machine, and the second parameter is the command name. In our case, the command name is java
. In return, it outputs some details about the command like the Command Type, the name of the executable executed on command, the version, and the executable source. The source is where Java is located.
PS C:\User> gcm -All java
Output:
CommandType Name Version Source
----------- ---- ------- ------
Application java.exe 15.0.1.0 C:\User\.jdks\openjdk-15...
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 Files\Java. 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 Files\Java. The directory you’re looking for should have the name of the JDK version, such as C:\Program Files\Java\jdk-19.
- If you installed the JRE instead of the JDK, you’ll have something like C:\Program Files\Java\jre1.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 Files\Java\jdk-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 Files\Java\jdk-19\bin or C:\Program Files\Java\jre1.8.0_351\bin.
- 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.
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 334,138 times.
Is this article up to date?
Ответы
Для проверки переменной JAVA_HOME
можно выполнить следующие действия:
- Откройте командную строку или терминал в зависимости от вашей операционной системы.
- Введите команду
echo %JAVA_HOME%
(вWindows
) илиecho $JAVA_HOME
(вUnix-подобных системах
) и нажмитеEnter
- Если переменная
JAVA_HOME
установлена, вы увидите путь к установленной версииJava
- Если вы видите сообщение «JAVA_HOME не установлен», значит, переменная не была установлена или была установлена неправильно.
- Если переменная была неправильно установлена, то нужно установить ее заново и правильно указать путь к установленной версии
Java
Курсы по программированию на Хекслете
Backend-разработка
Разработка серверной части сайтов и веб-приложений
Frontend-разработка
Разработка внешнего интерфейса сайтов и веб-приложений и верстка
Создание сайтов
Разработка сайтов и веб-приложений на JS, Python, Java, PHP и Ruby on Rails
Тестирование
Ручное тестирование и автоматизированное тестирование на JS, Python, Java и PHP
Аналитика данных
Сбор, анализ и интерпретация данных на Python
Интенсивные курсы
Интенсивное обучение для продолжающих
DevOps
Автоматизация настройки локального окружения и серверов, развертывания и деплоя
Веб-разработка
Разработка, верстка и деплой сайтов и веб-приложений, трудоустройство для разработчиков
Математика для программистов
Обучение разделам математики, которые будут полезны при изучении программирования
JavaScript
Разработка сайтов и веб-приложений и автоматизированное тестирование на JS
Python
Веб-разработка, автоматическое тестирование и аналитика данных на Python
Java
Веб-разработка и автоматическое тестирование на Java
PHP
Веб-разработка и автоматическое тестирование на PHP
Ruby
Разработка сайтов и веб-приложений на Ruby on Rails
Go
Курсы по веб-разработке на языке Go
HTML
Современная верстка с помощью HTML и CSS
SQL
Проектирование базы данных, выполнение SQL-запросов и изучение реляционных СУБД
Git
Система управления версиями Git, регулярные выражения и основы командой строки