Как прописать java home windows

Переменная окружения 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 – это важный шаг для работы с приложениями. Без правильно заданной переменной окружения многие инструменты могут работать некорректно или не запускаться вовсе. Настроив систему один раз, можно избежать множества проблем и сосредоточиться на разработке.

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Быстрый ответ

Для конфигурации переменных среды Java в ОС Windows следуйте инструкциям ниже:

  1. Укажите путь к установленной Java, например: C:\Program Files\Java\jdk-18.0.1.

  2. Настройте переменную JAVA_HOME:

  3. Добавьте путь к каталогу bin Java в переменную Path:

Теперь вы способны запустить инструменты Java (java, javac) из командной строки.

Кинга Идем в IT: пошаговый план для смены профессии

Полное руководство по переменным среды Java

Настройка JAVA_HOME и Path

Переменная JAVA_HOME указывает местоположение Java Development Kit (JDK):

Добавление пути к директории bin JDK к системной переменной Path разрешит вам обращаться к командам Java из любого места:

Установка JAVA_TOOL_OPTIONS

При помощи JAVA_TOOL_OPTIONS вы можете задать кодировку Unicode для вашего приложения:

Работа с Classpath

Не стоит устанавливать глобальную переменную CLASSPATH. Предпочтительнее управлять ею для каждого приложения индивидуально, используя ключи -cp или -classpath:

Проверка и устранение проблем

После изменения переменных убедитесь в правильности настройки:

Если вы столкнулись с проблемами, возможно, понадобится перезагрузка компьютера или переустановка JDK.

Визуализация

Принцип работы установки переменных:

  • JAVA_HOME — это место, где «живёт» Java, откуда начинается её работа.
  • Path — это путь, по которому Java передвигается, выполняя задачи.

Правильно настроенные переменные среды выглядят так:

Такая конфигурация обеспечивает надёжное и ясное взаимодействие ваших программ.

Умные советы для опытных пользователей

Быстрый доступ к переменным среды

Для быстрого доступа к окну переменных среды используйте комбинацию Win + R, введите sysdm.cpl и перейдите к разделу «Дополнительные параметры системы».

«Rapid Environment Editor» облегчит редактирование переменных среды.

Временная настройка переменных

Вы можете временно переопределить путь в командной строке:

Персонализация опций Java

Воспользуйтесь различными опциями запуска Java для настройки под специфические требования вашего приложения:

Обновление JDK

При обновлении JDK не забудьте также обновить ссылки на него в JAVA_HOME и Path.

Полезные материалы

  1. Как установить переменные Path и среды в Windows — подробное руководство, демонстрирующее основы работы с переменными среды в ОС Windows.
  2. PATH и CLASSPATH (Справочник по Java™) — документация Oracle, объясняющая, как управлять переменной PATH.
  3. Обсуждение настройки переменных среды для Java в ОС Windows на Stack Overflow — полезная ветка форума со множеством примеров и советов.
  4. Руководство Microsoft по управлению переменными среды — актуально для всех версий ОС Windows.
  5. Настройка JAVA_HOME для Apache Tomcat — описание процесса в контексте установки Tomcat.
  6. Видеоурок по установке Java JDK на ОС Windows 10 с настройкой JAVA_HOME — наглядное пособие для новичков.
  7. Как установить Java Software Development Kit — пошаговое руководство с иллюстрациями от WikiHow.

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.
  1. Step 1 Find your Java installation directory.

    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.
  2. Step 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. Step 3 Click the Environment Variables button.

    You’ll see it at the bottom-right corner of the System Properties window.

  4. Step 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 JDK installations and want to change JAVA_HOME to your new installation, select the current JAVA_HOME user variable and click Edit… instead.
  5. Step 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. Step 6 Enter the full path to your JDK installation.

    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.
  7. Step 7 Click OK.

    This takes you back to the Environment Variables window.

  8. Step 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. Step 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 JDK with \bin at the end. For example, C:\Program Files\Java\jdk-23.0.2\bin.
    • Click OK.
  10. Step 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.
  11. Advertisement

  1. Step 1 Open a Terminal window.

    To open Terminal, search for Terminal in Spotlight. You can also open Finder, click the Go menu, select Utilities, and choose the Terminal app.

  2. Step 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. Step 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. Step 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. Step 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-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.
    • export PATH=$JAVA_HOME/bin:$PATH
    • Save the file and exit the text editor when you’re finished.
  6. Step 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. Step 7 Type echo $JAVA_HOME and press ⏎ Return to confirm JAVA_HOME.

    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.
  8. Advertisement

  1. Step 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. Step 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-23-openjdk-arm64/bin/java. This is the directory you want.
  3. Step 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-23-openjdk-arm64" >> ~/.bashrc
    • echo "export PATH=$PATH:$JAVA_HOME/bin" >> ~/.bashrc
  4. Step 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.
  5. 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,561 times.

Is this article up to date?

Baeldung Pro comes with both absolutely No-Ads as well as
finally with Dark Mode, for a clean learning experience:

>> Explore a clean
Baeldung

Once the early-adopter seats are all used, the price will go
up and stay at $33/year.

Azure Container Apps is a fully managed serverless container
service that enables you to build and deploy modern,
cloud-native Java applications and microservices
at scale. It
offers a simplified developer experience while providing the
flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our
ecosystem, from a number of build options, managed Java components,
native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit
the documentation page.

You can also ask questions and leave feedback on the Azure
Container Apps GitHub page.

Azure Container Apps is a fully managed serverless container
service that enables you to build and deploy modern,
cloud-native Java applications and microservices
at scale. It
offers a simplified developer experience while providing the
flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our
ecosystem, from a number of build options, managed Java components,
native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you
can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure
Container Apps GitHub page.

Modern software architecture is often broken. Slow delivery
leads to missed opportunities, innovation is stalled due to
architectural complexities, and engineering resources are
exceedingly expensive.

Orkes is the leading workflow orchestration platform
built to enable teams to transform the way they develop, connect,
and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can
focus on building mission critical applications without worrying
about infrastructure maintenance to meet goals and, simply put,
taking new products live faster and reducing total cost of
ownership.

Try a 14-Day Free
Trial of Orkes Conductor today.

Modern software architecture is often broken. Slow delivery
leads to missed opportunities, innovation is stalled due to
architectural complexities, and engineering resources are
exceedingly expensive.

Orkes is the leading workflow orchestration platform
built to enable teams to transform the way they develop, connect,
and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can
focus on building mission critical applications without worrying
about infrastructure maintenance to meet goals and, simply put,
taking new products live faster and reducing total cost of
ownership.

Try a 14-Day
Free Trial of Orkes Conductor today.

Mocking is an essential part of unit testing, and the Mockito
library makes it easy to write clean and intuitive unit
tests
for your Java code.

Get started with mocking and improve your application tests
using our Mockito guide:

Download the
eBook

Handling concurrency in an application can be a tricky process
with many potential pitfalls. A solid grasp of the
fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with
our Java Concurrency guide:

>>
Download the eBook

Spring 5 added support for reactive programming with the Spring
WebFlux module, which has been improved upon ever since. Get
started with the Reactor project basics and reactive programming
in Spring
Boot:

>> Join Pro and
download the eBook

Since its introduction in Java 8, the Stream API has become a
staple of Java development. The basic operations like iterating,
filtering, mapping sequences of elements are deceptively simple to
use.

But these can also be overused and fall into some common
pitfalls.

To get a better understanding on how Streams work and how
to combine them with other language features, check out our guide
to Java Streams:

>> Join Pro
and download the eBook

Get started with Spring and Spring Boot, through the Learn
Spring
course:

>> LEARN
SPRING

Yes, Spring Security can be complex, from the more advanced
functionality within the Core to the deep OAuth support in the
framework.

I built the security material as two full courses — Core and
OAuth
, to get practical with these more complex scenarios. We
explore when and how to use each feature and code through it on
the backing project
.

You can explore the course here:

>> Learn Spring
Security

All Access is finally out, with all of my Spring courses. Learn
JUnit is out as well, and Learn Maven is coming fast. And, of
course, quite a bit more affordable. Finally.

>> GET THE
COURSE

Spring Data JPA is a great way to handle the complexity of
JPA with the powerful simplicity of Spring Boot
.

Get started with Spring Data JPA through the guided reference
course:

>> CHECK OUT THE
COURSE

End-to-end testing is a very useful method to make sure that
your application works as intended. This highlights issues in
the overall functionality
of the software, that the unit and
integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that
automates end-to-end testing, and supports all modern
browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based
test execution platform) it can be further scaled to run the
Playwright scripts in parallel across 3000+ browser and device
combinations:

>>
Automated End-to-End Testing With Playwright

Yes, we’re now running our Spring Sale. All Courses are
25% off until 26th May, 2025:

>> EXPLORE
ACCESS NOW

DbSchema is a super-flexible database designer, which can
take you from designing the DB with your team all the way to
safely deploying the schema
.

The way it does all of that is by using a design model, a
database-independent image of the schema, which can be shared in a
team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to
interact with the database using diagrams, visually compose
queries, explore the data, generate random data, import data or
build HTML5 database reports.

>> Take a
look at DBSchema

Yes, we’re now running our Spring Sale. All Courses are
25% off until 26th May, 2025:

>> EXPLORE
ACCESS NOW

1. Overview

In this quick tutorial, we’ll take a look at how to set the JAVA_HOME variable on Windows, Mac OS X, and Linux.

2.1. Windows 11

  1. Let’s locate the directory where the JDK is installed on our system, and note down the path to this directory.
  2. Right-click on the Windows Start button and select System.
  3. In the System window, click on Advanced System Settings on the left sidebar.
  4. In the System Properties window (Advanced tab):
    • Click the Environment Variables button.
    • Under the System Variables section, find JAVA_HOME.
    • Click Edit to modify the existing variable, or New to create a new one.
    • In the Variable Name field, enter JAVA_HOME.
    • In the Variable Value field, enter the path to our JDK installation directory (e.g., C:\Program Files\Java\jdk1.x.x_xx).
  5. In the System Properties window, select the Path variable under the System Variables section. Click Edit, and add %JAVA_HOME%\bin to the list of paths if it’s not already there.
  6. Click OK to apply the changes and restart the computer to ensure the changes take effect.

2.2. Windows 8 and 10

  1. Open Search and type advanced system settings.
  2. In the shown options, select the View advanced system settings link.
  3. Under the Advanced tab, click Environment Variables.
  4. In the System variables section, click New (or User variables for single user setting).
  5. Set JAVA_HOME as the Variable name, and the path to the JDK installation as the Variable value, and then click OK.
  6. Click OK and then Apply to apply the changes.

2.3. Windows 7

  1. On the Desktop, right-click My Computer and select Properties.
  2. Under the Advanced tab, click Environment Variables.
  3. In the System variables section, click New (or User variables for single user setting).
  4. Set JAVA_HOME as the Variable name, and the path to the JDK installation as the Variable value, and click OK.
  5. Click OK and then Apply to apply the changes.

Open Command Prompt and check the value of the JAVA_HOME variable:

echo %JAVA_HOME%

The result should be the path to the JDK installation:

C:\Program Files\Java\jdk1.8.0_111

Note that it’s still necessary to restart the computer to ensure the changes take effect in all applications.

3.1. Single User – Mac OS X 10.5 or Newer

In OS X 10.5, Apple introduced a command line tool (/usr/libexec/java_home) that dynamically finds the top Java version specified in Java Preferences for the current user.

Open ~/.bash_profile in any text editor and add the following:

export JAVA_HOME=$(/usr/libexec/java_home)

Then save and close the file.

Open a Terminal and run the source command to apply the changes:

source ~/.bash_profile

Now we can check the value of the JAVA_HOME variable:

echo $JAVA_HOME

The result should be the path to the JDK installation:

/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home

3.2. Single User – Mac OS X Older Versions

For older versions of OS X, we have to set the exact path to the JDK installation.

Open ~/.bash_profile in any editor and add the following:

export JAVA_HOME=/path/to/java_installation

Then save and close the file.

Open a Terminal and run the source command to apply the changes:

source ~/.bash_profile

Now we can check the value of the JAVA_HOME variable:

echo $JAVA_HOME

The result should be the path to the JDK installation:

/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home

3.3. Global Setting

To set JAVA_HOME globally for all users, the steps are the same as for a single user, but we use the file /etc/profile.

4. Linux

Here we’re going to manipulate the PATH, so these are the detailed instructions on how to do it.

4.1. Single User

To set JAVA_HOME in Linux for a single user, we can use /etc/profile or /etc/environment (preferred for system-wide setting) or ~/.bashrc (user-specific setting).

Open ~/.bashrc in any text editor and add the following:

export JAVA_HOME=/path/to/java_installation

Then save and close the file.

Run the source command to load the variable:

source ~/.bashrc

Now we can check the value of the JAVA_HOME variable:

echo $JAVA_HOME

The result should be the path to the JDK installation:

/usr/lib/jvm/java-8-oracle

4.2. Global Setting

To set JAVA_HOME in Linux for all users, we can use /etc/profile or /etc/environment (preferred).

Open /etc/environment in any text editor and add the following:

JAVA_HOME=/path/to/java_installation

Please note that /etc/environment isn’t a script, but a list of assignment expressions (that’s why export isn’t used). This file is read at the time of login.

To set JAVA_HOME using /etc/profile, here’s what we’ll add to the file:

export JAVA_HOME=/path/to/java_installation

Run the source command to load the variable:

source /etc/profile

Now we can check the value of the JAVA_HOME variable:

echo $JAVA_HOME

The result should be the path to the JDK installation:

/usr/lib/jvm/java-8-oracle

5. Conclusion

In this article, we covered how to set the JAVA_HOME environment variable on Windows, Mac OS X, and Linux.

Во многих статьях в интернете, документации к инструментам для разработки на 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, где она используется и как её корректно указать.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как установить ограничение по времени на компьютер windows 10
  • В какой папке находятся средства отладки windows
  • Не видит флешку windows 10 пишет нет носителя
  • Turn off windows update device driver searching
  • Indexing service windows server