Во многих статьях в интернете, документации к инструментам для разработки на 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, где она используется и как её корректно указать.
Чтобы проверить переменную JAVA_HOME
в операционной системе, можно использовать следующие команды:
- На Windows:
Откройте командную строку (cmd.exe
) и введите следующую команду:
echo %JAVA_HOME%
Если переменная JAVA_HOME
установлена, будет выведен путь к каталогу, где установлена Java Development Kit (JDK).
- На Linux/Unix/macOS:
Откройте терминал и введите следующую команду:
echo $JAVA_HOME
Если переменная JAVA_HOME
установлена, будет выведен путь к каталогу, где установлена Java Development Kit (JDK).
Если команда не выводит ничего или выводит сообщение об ошибке, это означает, что переменная JAVA_HOME
не установлена в системе.
Переменная JAVA_HOME
обычно устанавливается во время установки Java Development Kit (JDK) и указывает на местоположение установленной JDK.
Переменная окружения JAVA_HOME – это один из ключевых параметров, необходимых для работы множества инструментов, таких как Gradle, Maven, Tomcat, Android Studio и других. Если она не настроена или указана неправильно, многие приложения могут не запускаться, а сборка проектов – выдавать ошибки.
Эксперты рекомендуют
Что такое JAVA_HOME?
– это переменная окружения, которая указывает системе путь к установленному JDK. Она необходима для правильной работы различных инструментов разработки, компиляторов, серверных приложений.
Чем отличается от PATH?
JAVA_HOME хранит путь к установленному JDK и помогает программам находить нужную версию.
PATH содержит список директорий, в которых система ищет исполняемые файлы. Если в PATH не указан путь, команда может не работать.
Почему важно правильно настроить JAVA_HOME?
Если переменная не настроена, система может использовать устаревшую или неподходящую версию. Это приводит к ошибкам при запуске приложений, проблемам с компиляцией и сбоям в работе инструментов сборки.
Настройка позволяет избежать таких проблем и обеспечивает корректную работу всех зависимых программ.
Как определить, задана ли переменная?
Windows:
Открыть Командную строку. Ввести команду: echo %JAVA_HOME%. Если не задана, отобразится пустая строка или сообщение об ошибке.
macOS и Linux:
Открыть Терминал. Ввести команду: echo $JAVA_HOME. Если не настроена, вывод будет пустым.
Настройка в Windows
1. Найдите путь к установленному JDK
Откройте Проводник и перейдите в папку: C:\Program Files\Java. Внутри этой директории найдите папку с установленной версией. Откройте папку и скопируйте полный путь.
2. Добавление
- Откройте Панель управления.
- Перейдите в Система → Дополнительные параметры.
- Нажмите Переменные.
- В разделе Системные переменные нажмите Создать.
- В поле Имя введите: JAVA_HOME
- В поле Значение вставьте скопированный ранее путь.
- Нажмите ОК.
3. Добавление в PATH
В списке Системные переменные найдите Path. Нажмите Изменить → Создать. Вставьте: %JAVA_HOME%\bin. Сохраните изменения.
4. Проверка
Откройте Командную строку (cmd) и введите: java -version. Если все прошло успешно, отобразится установленная версия.
Настройка в macOS, Linux
1. Найдите путь
Выполните команду: /usr/libexec/java_home. Она отобразит путь к установленному JDK, например.
2. Установка
Откройте файл конфигурации: nano ~/.zshrc. Добавьте строку: export JAVA_HOME=$(/usr/libexec/java_home). Сохраните файл и обновите настройки.
3. Проверка настройки
Выполните команду: echo $JAVA_HOME. Если путь отображается корректно, настройка завершена.
Как автоматизировать выбор версии?
Если на вашей системе установлено несколько вариантов JDK, можно настроить автоматический выбор нужной версии с помощью утилит, таких как SDKMAN! для Linux и macOS, или с помощью JEnv. Эти инструменты позволяют легко переключаться без необходимости вручную редактировать переменную.
Преимущества использования SDKMAN! или JEnv:
- Простота в переключении между версиями JDK.
- Удобство работы с несколькими версиями для различных проектов.
- Автоматическая настройка.
- Поддержка множества инструментов и фреймворков
- Простота в обновлениях
- Удобный интерфейс командной строки
Как выбрать подходящую версию для проекта?
1. Требования проекта:
Для различных фреймворков и библиотек могут понадобиться разные версии. Например, JDK 8 подходит для старых приложений, а для современных технологий лучше выбрать JDK 11 или 17.
2. LTS:
Если проект требует долгосрочной поддержки, выбирайте LTS, которые обеспечат стабильность и регулярные обновления безопасности.
3. Тестирование:
Тестирование на нескольких версиях поможет убедиться, что все компоненты работают корректно. Инструменты, такие как SDKMAN! или JEnv, позволяют легко переключаться между версиями.
4. Преимущества новых версий:
Новые JDK предлагают улучшения в производительности и поддержке многозадачности, что полезно для приложений с высокими требованиями.
Сравнение установки в разных ОС
Настройка в разных ОС имеет свои особенности, связанные с управлением переменными окружения. В таблице ниже представлена детальная информация о процессе настройки.
ОС |
Где установить |
Файл конфигурации |
Как обновить |
Требуется ли перезагрузка? |
Windows | Панель управления → Система → Дополнительные параметры → Переменные | Отдельного файла конфигурации нет, настройки хранятся в Переменных Windows | Перезапустить терминал | Да (для применения изменений во всех программах) |
macOS | Файл ~/.zshrc (для zsh) или ~/.bash_profile (для bash) | ~/.zshrc (для zsh) или ~/.bash_profile (для bash) | source ~/.zshrc или source ~/.bash_profile | Нет, достаточно обновить конфигурацию с помощью source |
Linux | Файл ~/.bashrc или ~/.bash_profile | ~/.bashrc (для текущего пользователя) или /etc/profile (для всех пользователей) | source ~/.bashrc | Нет, достаточно обновить конфигурацию |
Почему в Windows требуется перезагрузка?
После изменения переменных окружения в Windows многие приложения и терминалы продолжают использовать старые конфигурации. Перезагрузка ОС гарантирует, что все программы увидят обновленный вариант. В macOS и Linux достаточно выполнить команду source ~/.bashrc или source ~/.zshrc, чтобы изменения вступили в силу.
Ошибки и способы их устранения
Большинство ошибок связаны с некорректными путями или забытыми конфигурациями. Важно указывать путь, добавлять в PATH, а после изменений перезапускать терминал. Соблюдение этих рекомендаций обеспечит стабильную работу приложений.
1. Система сообщает, что переменная не задана:
Отсутствует либо указана неправильно, поэтому система не может ее найти. Проверьте, зарегистрирована ли в окружении. Если значение пустое, добавьте путь. В Windows потребуется перезагрузка, в macOS и Linux – перезапуск терминала.
2. Указан неверный путь:
Часто ссылается на JRE вместо JDK, содержит ошибки или устарел после обновления. Определите актуальную директорию и укажите ее, избегая ссылок на JRE или bin.
3. Команда ‘java’ не распознается:
Отсутствует в PATH, поэтому система не может найти исполняемый файл. Добавьте bin из JDK в PATH через конфигурации среды, затем перезапустите терминал. В Windows может потребоваться перезагрузка.
4. Пробелы:
Некоторые инструменты не поддерживают пути с пробелами, например, *C:\Program Files\Java* в Windows.
Используйте кавычки либо короткий формат.
5. Используется не та версия:
При наличии нескольких версий система может обращаться к устаревшей. Определите активную, убедитесь, что путь ведет к нужной, обновите настройки, затем перезапустите терминал.
6. Изменения не вступают в силу:
Система продолжает использовать старые значения, поскольку обновления не применились. Закройте и откройте терминал заново. В Windows возможна необходимость перезагрузки, в macOS и Linux – обновления конфигурации.
7. Настроена, но система не работает:
Путь указан неверно, JDK не установлен или отсутствует в PATH. Проверьте наличие Java, убедитесь, что путь правильный, при необходимости добавьте в PATH.
Реальная история успеха
Илья, начинающий разработчик, столкнулся с проблемой при компиляции приложений: несмотря на установленный JDK, система не могла найти Java. Он понял, что проблема заключалась в отсутствии переменной. После настройки все заработало, и проект был успешно завершён. Через несколько месяцев Илья устроился в IT-компанию, где занимается разработкой серверных приложений и теперь помогает коллегам с настройкой окружения.
Заключение
Настройка JAVA_HOME – это важный шаг для работы с приложениями. Без правильно заданной переменной окружения многие инструменты могут работать некорректно или не запускаться вовсе. Настроив систему один раз, можно избежать множества проблем и сосредоточиться на разработке.
How do programs that need Java find it on your operating system? They search for JAVA_HOME. Here’s how to set it up on your Windows machine.
For Java-based programs such as Maven, Jenkins, Gradle or Tomcat to run, they need to know that Java’s JDK is installed. That’s the purpose of the JAVA_HOME environment variable. It tells programs where to find the Java installation.
3 ways to set JAVA_HOME on Windows
You can set JAVA_HOME on Windows in one of three ways:
- Allow the Java installer to do it.
- Use the environment variable editor.
- Set JAVA_HOME at the command line.
Automatically set JAVA_HOME
Java installers have come a long way over the years.
In the past to install Java one had to download ZIP files, with manual extractions and extensive configuration. Today, you can download an installer that not only installs Java but also configures the PATH and JAVA_HOME environment variables.
For example, with the Eclipse Temurin version of the JDK, setting JAVA_HOME is simply a matter of choosing the option to set or override the JAVA_HOME variable on the third step of the installer.
How to set JAVA_HOME through Windows
If you choose to install Java manually or you want to update the JAVA_HOME environment variable on Windows, the easiest route is to use the Windows environment variables editor. To do so, follow these steps:
- Open the Windows System Properties window.
- Choose Advanced System settings.
- Click on the Environment Variables button.
- Click on the New button under System Variables.
- Set JAVA_HOME as the environment variable name.
- Set the location of the JDK installation as the environment variable Value.
- Click OK and close the JAVA_HOME environment variable editor.
Remember that JAVA_HOME points to the root folder into which the JDK was installed. Do not point JAVA_HOME to the \bin directory of the install. The PATH variable points to \bin, while JAVA_HOME points to the root folder into which the JDK was installed.
How to set JAVA_HOME at the command line
For those who prefer to use the command line, you can easily set JAVA_HOME on Windows with any terminal window, be it PowerShell, the Command Prompt or even Git’s Bash shell.
The following command permanently points JAVA_HOME to the location you set:
setx JAVA_HOME -m «C:\_jdk25.0»
The option to manually set JAVA_HOME through the command line is especially useful if you need to quickly update JAVA_HOME to point to a newer installation of the JDK, or if you need to regularly switch between Java versions.
How to echo JAVA_HOME in Windows
After you set JAVA_HOME in Windows, it’s a good idea to verify the change has persisted. The easiest way to do this is to echo JAVA_HOME in a command prompt or a Bash shell.
To echo JAVA_HOME in a DOS prompt, simply bookend the variable with percentage signs, like so:
@REM How to echo JAVA_HOME in windows
echo %JAVA_HOME%
>> C:\_jdk25.0
If you use a Bash shell, or if you have set JAVA_HOME in an Ubuntu environment and need to echo JAVA_HOME in Linux, place a single dollar sign before the environment variable: echo $JAVA_HOME.
If the echo command returns the value you set for JAVA_HOME, you know your system is configured properly.
Cameron McKenzie has been a Java EE software engineer for 20 years. His current specialties include Agile development; DevOps; Spring; and container-based technologies such as Docker, Swarm and Kubernetes.
Dig Deeper on Core Java APIs and programming techniques
-
Install Java’s JDK on Ubuntu
By: Cameron McKenzie
-
How to download and install Java 21 on Windows
By: Cameron McKenzie
-
How to install Java 21 on Ubuntu
By: Cameron McKenzie
-
Tips for migrating to OpenJDK
Download Article
Easy ways to set the JAVA_HOME environment variable
Download Article
- Windows
- Mac
- 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), 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.
Setting Java Home: Fast Facts
- To set JAVA_HOME, you’ll need the full path to your JDK or JRE installation.
- On Windows, you’ll set JAVA_HOME in Advanced System Settings > Environment Variables.
- On a Mac, you’ll need to add the Java path to your .zshrc file in a Terminal.
- On Linux, you can add the Java path to your .bashrc.
-
Assuming that you didn’t change the path for the JDK during installation, 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-23.
- 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.
-
Here’s how:
- Press the Windows key on your keyboard and type advanced system.
- Click View advanced system settings in the search results.
Advertisement
-
You’ll see it at the bottom-right corner of the System Properties window.
-
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 JDK installations and want to change JAVA_HOME to your new installation, select the current JAVA_HOME user variable and click Edit… instead.
-
- If you’re editing the current JAVA_HOME path, you’ll already have JAVA_HOME here. So, you can skip this step.
-
For example, if the path is C:\Program Files\Java\jdk-23, 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.
-
This takes you back to the Environment Variables window.
-
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.
-
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 JDK with \bin at the end. For example, C:\Program Files\Java\jdk-23.0.2\bin.
- Click OK.
-
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
-
To open Terminal, search for Terminal in Spotlight. You can also open Finder, click the Go menu, select Utilities, and choose the Terminal app.
-
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.
-
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.
-
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.
-
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-23.0.2.jdk/Contents/Home
- Replace
/Library/Java/JavaVirtualMachines/jdk-23.0.2.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.
-
-
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).
-
You should now see the full path to JAVA_HOME.
- If you have any other open windows attempting to find Java binaries, close and reopen them.
Advertisement
-
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.
-
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-23-openjdk-arm64/bin/java. This is the directory you want.
-
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-23-openjdk-arm64" >> ~/.bashrc
echo "export PATH=$PATH:$JAVA_HOME/bin" >> ~/.bashrc
-
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 378,412 times.