Windows add java home

Как установить JAVA_HOME в Windows 10

В терминологии Unix переменная окружения – это строка, содержащая такую ​​информацию, как имя диска, имя пути, имя файла и т. Д. JAVA_HOME – это переменная среды, которая обращается к каталогу, где находится среда выполнения Java или Java Development Kit. установлен в системе. Точнее сказать, если вы установили Java по пути C: \ Program Files \ Java \ jdk1.8.0_121 на своем компьютере, то ваш Java_Home будет C: \ Program Files \ Java \ jdk1.8.0_121 . По сути, JAVA_Home – это просто пример, используемый программами на основе Java, такими как Apache Tomcat и другими инструментами сервера приложений, для определения местоположения Java в системе.

Эти сторонние программы используют переменные окружения, которые указывают на каталог JDK или JRE. Проще говоря, это позволяет программам легко находить исполняемый файл каталога, такой как javac, на компьютере. Если вы не используете эти сторонние программы, пользователям может быть необязательно устанавливать JAVA_Home в вашей системе. В этой статье мы подробно объясним, как установить JAVA_HOME в качестве переменной среды в Windows 10.

Настройка JAVA_HOME в Windows 10

Установите переменную среды JAVA_HOME и обновите системный путь

Загрузите и установите Java с официального сайта – java.com .

После установки перейдите в меню Пуск и введите Дополнительные параметры системы.

Нажмите Просмотреть дополнительные настройки системы в списке, чтобы открыть Свойства системы.

Перейдите на вкладку Дополнительно и нажмите кнопку Переменная среды .

В окне «Переменная среды» нажмите кнопку Создать под системной переменной.

В системной переменной Изменить укажите имя переменной в виде JAVA_HOME и значение переменной в качестве пути к каталогу JDK.

Нажмите ОК .

Теперь вернитесь в окно переменной среды и выберите путь в системной переменной.

Нажмите кнопку Изменить , чтобы открыть окно Изменить переменную среды.

Нажмите кнопку «Создать» и введите % JAVA_HOME% \ bin .

Нажмите ОК , чтобы применить изменения.

Проверьте настройки конфигурации JAVA_HOME, используя CMD

Чтобы проверить свою конфигурацию, откройте Командную строку .

Введите echo% JAVA_HOME% и нажмите Enter. Это должно напечатать каталог JDK, на который указывает JAVA_HOME. Вместо этого, если вы видите пробел, это означает, что вы не смогли настроить переменную среды.

Далее введите javac -version , который должен печатать версию компилятора Java.

Если нет, то будет напечатано сообщение о том, что javac не распознается как внутренняя или внешняя команда. Это означает, что переменная пути установлена ​​неправильно.

Windows add java home

На сегодня местонахождения файлов для скачивания JDK находится по адресу Java SE Downloads
Думаю, что вы можете взять самый последний JDK — в нашем курсе это JDK 1.7 update 3. Но еще раз повторюсь — принципиальных отличий в установке вы не увидите. Ваша задача — найти версию JDK, которая установится на ваш компьютер — выберите операционную систему и разрядность.

Шаг 2: Установить JDK из файла

Здесь тоже каких-либо сложностей быть не должно — я не видел принципиальной разницы между версиями 1.4, 1.5, 1.6 и 1.7. Запускаем скачанный файл и после некоторого ожидания вы увидите стартовый экран для установки. Нажимаем «Next».

На следующем экране вам предложат директорию для установки. Мне больше нравится установка не в директорию по умолчанию. (она выделена красным). Нажмите кнопку «Change…».

В появившемся окне установите директорию «C:\Java\jdk1.7.0_03». После этого я вам настоятельно советую выделить этот путь и сохранить его в буфере обмена (чуть позже мы им воспользуемся). Дальше жмем «OK».

После этого можно увидеть установленную директорию в окне. Снова нажимаем кнопку «Next».

Через некоторое время установка JDK почти закончится, но вам также придется установить JRE (Java Runtime Environment). Вы это сразу увидите по форме, которая должна появиться. Здесь нет необходимости менять директорию — смело жмем «Next».

Какое-то время перед вами будет экран, на котором будет говориться, что 3 миллиарда устройств используют Java.

И наконец вы увидите, что установка закончилась.

В версии 1.7 появился еще один шаг — выбор установки JavaFX 2.0. У вас появиться экран для выбора директории (мне не очень понравилось, как он реализован). Но в общем можно просто нажимать кнопку «Next». Т.к. я плохо отношусь к диреториям с пробелом, то я выбрал свой вариант.

Шаг 3: Установка переменных среды — JAVA_HOME и PATH

На этом установка практически завершена. Останется сделать только еще один шаг — прописать путь до файлов JDK в путях операционной системы. Это позволит нам запускать основные файлы из командной строки — удобный момент. И также мы установим переменную JAVA_HOME — это правда нам пригодится не скоро, но сделаем это прямо сейчас. Думаю, что большинство из вас знает как это сделать. Но давайте все-таки это сделаем вместе. Я использую ОС Windows 7.0 — поэтому буду демонстрировать на ней. В меню «Пуск» найдите пункт «Компьютер» и щелкните на нем правой кнопкой мыши. В появившемся меню выберите пункт «Свойства». Появится окно

Читайте также:  Windows server 2008r2 мы windows server 2012

Выбираем пункт «Дополнительные параметры системы» (я выделил этот пункт). Получим окно, в котором надо выбрать пункт «Переменные среды».

В появившемся окне вам надо создать одну переменную — «JAVA_HOME». И отредактировать переменную «Path». Для этого нажимаем кнопку «Создать».

Вариант установки переменной «JAVA_HOME» показано на рисунке. Вот тут как раз и пригодится та строка, которую я предлагал вам запомнить при установке JDK.

Для установки переменной «Path» скорее всего ее создавать не надо — она уже обычно есть. Так что надо ее найти в списке и нажать кнопку «Изменить». Но будьте внимательны — во-первых здесь надо вводить строку предварительно поставив «;» в конце списка всех путей. И во-вторых — надо добавить строку «\bin» после. Пример показан на рисунке.

И еще раз — БУДЬТЕ ВНИМАТЕЛЬНЫ при редактировании PATH — она содержит важную информацию. Не надо ее целиком стирать и оставлять только свою строку. Надо после точки с запятой ДОБАВИТЬ строку до каталога с JDK (+ строка «\bin»). Т.е. если у вас JDK установлен в каталог C:\Java\jdk1.7, то в PATH надо добавить (через «;») строку C:\Java\jdk1.7\bin.
Теперь мы сделали все необходимые шаги для установки JDK — пора приступать к написанию простой программы. Основные шаги

How to set JAVA_HOME on Windows 10?

This tutorial shows you how to set a JAVA_HOME system variable on Windows 10.

1. Advanced System Settings

Type advanced system settings in the search box (beside the Windows start button), clicks View advanced system settings .

2. Environment Variables

Select Advance tab, clicks Environment Variables

3. Add JAVA_HOME

In System variables, clicks New. button to add a new JAVA_HOME variable and point it to the JDK installed folder.

  1. Correct – C:\Program Files\Java\jdk1.8.0_60
  2. Wrong – C:\Program Files\Java\jdk1.8.0_60\bin

4. Update PATH

In System variables, find PATH , clicks edit. button :

4.1 In old version of Windows, it will prompt you below dialog box to edit the values directly, append this %JAVA_HOME%\bin; to the end of the line.

4.2 In latest Windows 10, it will prompt you below dialog box, clicks on New button, and add this %JAVA_HOME%\bin

Переменная окружения JAVA_HOME – что это такое и она нужна

Во многих статьях в интернете, документации к инструментам для разработки на Java и в книгах зачастую упоминается JAVA_HOME. Что же такое 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) и укажите последовательно укажите две команды:

Если вы правильно установили JDK/JRE и правильно установили переменные окружения, вы увидите вывод наподобие этого:

Это будет служить результатом того, что переменная JAVA_HOME установлена правильно и Java работает из командной строки.

Резюме

В данной статье мы рассказали вам, что являет собой переменная окружения JAVA_HOME, где она используется и как её корректно указать.

How to set java_home on Windows 7?

I went to the Environment Variables in ‘System’ in the control panel and made two new variables, one for user variables and one for system variables. Both were named JAVA_HOME and both pointing to

But for some reason, I still get the below error when running a Java command.

Читайте также:  Work folders client windows 10 можно ли отключить

How can I fix this problem?

18 Answers 18

Find JDK Installation Directory

First you need to know the installation path for the Java Development Kit.

Open the default installation path for the JDK:

There should be a subdirectory like:

Note: one has only to put the path to the jdk without /bin in the end (as suggested on a lot of places). e.g. C:\Java\jdk1.8.0_172 and NOT C:\Java\jdk1.8.0_172\bin !

Set the JAVA_HOME Variable

Once you have the JDK installation path:

  1. Right-click the My Computer icon on your desktop and select Properties.
  2. Click the Advanced tab, then click the Environment Variables button.
  3. Under System Variables, click New.
  4. Enter the variable name as JAVA_HOME.
  5. Enter the variable value as the installation path for the Java Development Kit.
  6. Click OK.
  7. Click Apply Changes.

Note: You might need to restart Windows

The complete article is here, on my blog: Setting JAVA_HOME Variable in Windows.

What worked for me was adding the %JAVA_HOME%\bin to the Path environment variable with the JAVA_HOME environment variable pointing to the jdk folder.

You have to first Install JDK in your system.

JAVA_HOME = C:\Program Files\Java\jdk1.7.0 [Location of your JDK Installation Directory]

Once you have the JDK installation path:

  • Right-click the My Computer icon on
  • Select Properties.
  • Click the Advanced system setting tab on left side of your screen
  • Aadvance Popup is open.
  • Click on Environment Variables button.

  • Under System Variables, click New.
  • Enter the variable name as JAVA_HOME.
  • Enter the variable value as the installation path for the Java Development Kit.
  • Click OK.
  • Click Apply Changes.

Set JAVA Path under system variable

PATH= C:\Program Files\Java\jdk1.7.0; [Append Value with semi-colon]

In cmd (temporarily for that cmd window):

You need to set it to C:\Sun\SDK\jdk (Assuming that is where the JDK is installed — It is not the default) — Do not put the \bin in C:\Sun\SDK\jdk\bin .

If your app only runs when you are logged in as the current user then put it in the user variables — If it needs to run for all users on your system then put it in System variables.

You might also need to add %JAVA_HOME%\bin to the path also (Also it depends on whether you run it from just the user or from all users, including System)

Control Panel > Java, Java tab, click the View button. In Runtime Parameters, put:

Or when you execute Java you can add that command line switch to the command:

One Image can fix this issue.

For those who are still stumped with this problem (I tried all the above suggestions) —

If you’re on a 64-bit version of Windows and you’ve installed the 32-bit JDK, besides adjusting PATH variables, you may need to adjust registry variables, too.

I was pulling my hair out, having correctly set my PATH variables — still to no avail — and then only finding «vacated» Java entries in my registry, seemingly a deadend of fixing the «misfiring» Java Runtime Environment.

By using Process Monitor to watch the program I was trying to get started, in order to sniff out where it was looking in the registry for Java (Runtime Environment), I triumphantly discovered that it’s looking in the 32-bit version of registry entries, found in HKEY_LOCAL_MACHINE\SOFTWARE\**Wow6432Node**\JavaSoft\Java Runtime Environment .

Within that key, you should find subkeys of different Java versions installed (past and/or present). Click on the subkey of the latest version (my subkey is currently 1.7.0_25, for example). After clicking on that subkey, you’ll see registry string values listed on the right, and particularly, JavaHome and RuntimeLib . You need to modify the values of those two values to reflect the both the current folder and jvm.dll file, respectively.

For example, in my case, the values were (previously) respectively set at C:\Program Files (x86)\Java\jre7 and C:\Program Files (x86)\Java\jre7\bin\client\jvm.dll which are nonexistent on my machine. I had to update these to the current folder and file of C:\Program Files (x86)\Java\jdk1.7.0_25\jre and C:\Program Files (x86)\Java\jdk1.7.0_25\jre\bin\client\jvm.dll .

Again, this will depend entirely on both what version of Java (JDK and/or JRE) you have installed — 32 or 64-bit — and what type of operating system you’re on — 32 or 64-bit. Just know that they’re reflected in different locations within the registry (like the Wow6432Node for 32 bit applications, in my case with the 32-bit JDK installed on a 64-bit machine).

Now that I’ve updated those two registry values, my program runs flawlessly, with no more hiccups or complaints about a missing Java Runtime Environment (stemming from the registry).

This is the official solution for setting the Java environment from www.java.com — here.

There are solutions for Windows 7, Windows Vista, Windows XP, Linux/Solaris and other shells.

Example

Windows 7

  1. Select Computer from the Start menu
  2. Choose System Properties from the context menu
  3. Click Advanced system settings -> Advanced tab
  4. Click on Environment Variables, under System Variables, find PATH, and click on it.
  5. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  6. Reopen Command prompt window, and run your Java code.
Читайте также:  Исо файл windows 10

Windows 7

Go to Control Panel\All Control Panel Items\User Accounts using Explorer (not Internet Explorer!)

click on the Start button

click on your picture

Change my environment variables

New.

(if you don’t have enough permissions to add it in the System variables section, add it to the User variables section)

Add JAVA_HOME as Variable name and the JDK location as Variable value > OK

Test:

  • open a new console (cmd)
  • type set JAVA_HOME
    • expected output: JAVA_HOME=C:\Program Files\Java\jdk1.8.0_60

We need to make a distinction between the two environment variables that are discussed here interchangeably. One is the JAVA_HOME variable. The other is the Path variable. Any process that references the JAVA_HOME variable is looking for the search path to the JDK, not the JRE. The use of JAVA_HOME variable is not meant for the Java compiler itself. The compiler is aware of its own location. The variable is meant for other software to more easily locate the compiler. This variable is typically used by IDE software in order to compile and build applications from Java source code. By contrast, the Windows CMD interpreter, and many other first and third party software references the Path variable, not the JAVA_HOME variable.

Use case 1: Compiling from CMD

So for instance, if you are not using any IDE software, and you just want to be able to compile from the CMD, independent of your current working directory, then what you want is to set the Path variable correctly. In your case, you don’t even need the JAVA_HOME variable. Because CMD is using Path, not JAVA_HOME to locate the Java compiler.

Use case 2: Compiling from IDE

However, if you are using some IDE software, then you have to look at the documentation first of all. It may require JAVA_HOME to be set, but it may also use another variable name for the same purpose. The de-facto standard over the years has been JAVA_HOME, but this may not always be the case.

Use case 3: Compiling from IDE and CMD

If in addition to the IDE software you also want to be able to compile from the CMD, independent of your current working directory, then in addition to the JAVA_HOME variable you may also need to append the JDK search path to the Path variable.

JAVA_HOME vs. Path

If your problem relates to compiling Java, then you want to check the JAVA_HOME variable, and Path (where applicable). If your problem relates to running Java applications, then you want to check your Path variable.

Path variable is used universally across all operating systems. Because it is defined by the system, and because it’s the default variable that’s used for locating the JRE, there is almost never any problem running Java applications. Especially not on Windows where the software installers usually set everything up for you. But if you are installing manually, the safest thing to do is perhaps to skip the JAVA_HOME variable altogether and just use the Path variable for everything, for both JDK and the JRE. Any recent version of an IDE software should be able to pick that up and use it.

Symlinks

Symbolic links may provide yet another way to reference the JDK search path by piggybacking one of the existing environment variables.

I am not sure about previous versions of Oracle/Sun JDK/JRE releases, but at least the installer for jdk1.8.0_74 appends the search path C:\ProgramData\Oracle\Java\javapath to the Path variable, and it puts it at the beginning of the string value. This directory contains symbolic links to the java.exe, javaw.exe and javaws.exe in the JRE directory.

So at least with the Java 8 JDK, and presumably the Java 8 JRE standalone, no environment variable configuration needs to be done for the JRE. As long as you use the installer package to set it up. There may be differences on your Windows installation however. Note that the Oracle JRE comes bundled with the JDK.

If you ever find that your Java JDK configuration is using the wrong version of the compiler, or it appears to be working by magic, without being explicitly defined so (without casting the spell), then you may have a symlink somewhere in your environment variables. So you may want to check for symlink.

Оцените статью