Настройка 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,540 times.

Is this article up to date?

This article explains how to set JAVA_HOME environment variable on the Windows Operating system. The JAVA_HOME is an environment variable that points to the JDK (Java Development Kit) installation directory.

Table of Contents

Prerequisite

  • JDK (any version) should be Installed
  • Window OS

Note: In this tutorial, we are taking the example of JDK 19 which is already installed on the Windows 10 Operating system.

Why do we need JAVA_HOME environment variable?

The JAVA_HOME environment variable is used by the Java compiler, debugger, and other tools to locate the JDK (Java Development Kit). In order to use the JDK, it is important to set the JAVA_HOME environment variable so that the tools can find it. This variable should be configured on all Operating Systems that have a Java installation, including Windows, Ubuntu, Linux, Mac, and Android.

Follow the below steps properly, in order to set Java environment variables in your Windows machine. Here we will set JAVA_HOME and update the Path system variable.

1. Find Java Home Directory

First of all, you should find out where the JDK (Java Development Kit) is installed in your system. It is typically under the C:\Program Files\Java directory. As you can see in the below image, in our case it is installed at C:\Program Files\Java\jdk-19

set JAVA_HOME environment variable

2. Open System Environment Variables Dialog

To open the system environment variables dialog, you can type the ‘environment‘ in the Window search box and click on Edit the system environment variables as shown in the below image,

set JAVA_HOME environment variable on Windows

Now click on the Environment Variables button as follow, to open the Environment variable dialog.

set JAVA_HOME environment variable on Windows

3. Create JAVA_HOME Variable

In the Environment Variables dialog, click on the New button to add the JAVA_HOME variable as follow:

set JAVA_HOME environment variable on Windows

In the below dialog fill the details like Variable name: JAVA_HOME and Variable value: C:\Program Files\Java\jdk-19

set JAVA_HOME environment variable on Windows

After that, you should update the Path variable as shown in the sequence number in the below image,

set JAVA_HOME environment variable on Windows

How to Verify the JAVA_HOME System Environment Variable?

In order to verify the successful setup of the JAVA_HOME environment variable, you can open the Command Prompt by typing ‘cmd‘ in the Window search box as shown in the below image:

set JAVA_HOME environment variable on Windows

Once the Command Prompt is opened, type the command java -version and press Enter key. Now here you will see the java version getting displayed, it means you have successfully set up the JAVA_HOME environment variable on your Window machine.

set JAVA_HOME environment variable on Windows

Related articles:

  • Download JDK 19 and Install on Windows 10 (64-bit)
  • How to Download JDK 17 and Install on Windows 11 [64-bit]
  • How to Download and Install JDK 11 on Windows 10?
  • How to install Maven on Windows System
  • How to install and configure Tomcat Server in Eclipse?
  • Install MySQL Server 8.0.27 [zip Archive] on Windows 10

You may also like:

  • File Upload in Java Servlet Example
  • Spring Boot File Upload with Advance Progress bar in Ajax
  • How to write Excel files in java using Apache POI?
  • Drag and drop file upload using Javascript

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как обновить windows до нужной версии
  • 8000405 не найден сетевой путь windows 10
  • Настройка wifi в windows 2000
  • Что означают названия продуктов windows 10 в wsus
  • На рабочем столе ничего не отображается windows 10