Настройка переменной среды java windows

How to set the environment variables for Java in Windows (the classpath)?

xpt's user avatar

xpt

20.7k37 gold badges129 silver badges217 bronze badges

asked Nov 4, 2009 at 7:54

Dean jones's user avatar

5

Java SE Development Kit 8u112 on a 64-bit Windows 7 or Windows 8

Set the following user environment variables (== environment variables of type user variables)

  • JAVA_HOME : C:\Program Files\Java\jdk1.8.0_112
  • JDK_HOME : %JAVA_HOME%
  • JRE_HOME : %JAVA_HOME%\jre
  • CLASSPATH : .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
  • PATH : your-unique-entries;%JAVA_HOME%\bin (make sure that the longish your-unique-entries does not contain any other references to another Java installation folder.

Note for Windows users on 64-bit systems:

Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'

Notice that these environment variables are derived from the «root» environment variable JAVA_HOME. This makes it easy to update your environment variables when updating the JDK. Just point JAVA_HOME to the fresh installation.

There is a blogpost explaining the rationale behind all these environment variables.

Optional recommendations

  • Add a user environment variable JAVA_TOOL_OPTIONS with value -Dfile.encoding="UTF-8". This ensures that Java (and tools such as Maven) will run with a Charset.defaultCharset() of UTF-8 (instead of the default Windows-1252). This has saved a lot of headaches when wirking with my own code and that of others, which unfortunately often assume the (sane) default encoding UTF-8.
  • When JDK is installed, it adds to the system environment variable Path an entry C:\ProgramData\Oracle\Java\javapath;. I anecdotally noticed that the links in that directory didn’t get updated during an JDK installation update. So it’s best to remove C:\ProgramData\Oracle\Java\javapath; from the Path system environment variable in order to have a consistent environment.

starball's user avatar

starball

22.1k8 gold badges47 silver badges286 bronze badges

answered Oct 29, 2014 at 21:00

Abdull's user avatar

AbdullAbdull

26.5k26 gold badges130 silver badges172 bronze badges

15

In Windows inorder to set

Step 1 : Right Click on MyComputer and click on properties .

Step 2 : Click on Advanced tab

alt text

Step 3: Click on Environment Variables

alt text

Step 4: Create a new class path for JAVA_HOME

alt text

Step 5: Enter the Variable name as JAVA_HOME and the value to your jdk bin path ie c:\Programfiles\Java\jdk-1.6\bin and

NOTE Make sure u start with .; in the Value so that it doesn’t corrupt the other environment variables which is already set.

alt text

Step 6 : Follow the Above step and edit the Path in System Variables add the following ;c:\Programfiles\Java\jdk-1.6\bin in the value column.

Step 7 :Your are done setting up your environment variables for your Java , In order to test it go to command prompt and type

 java   

who will get a list of help doc

In order make sure whether compiler is setup Type in cmd

  javac

who will get a list related to javac

Hope this Helps !

Taylor Hx's user avatar

Taylor Hx

2,81523 silver badges36 bronze badges

answered Nov 4, 2009 at 9:08

Srinivas M.V.'s user avatar

Srinivas M.V.Srinivas M.V.

6,5085 gold badges33 silver badges49 bronze badges

6

— To set java path —

There are two ways to set java path

A. Temporary

  1. Open cmd
  2. Write in cmd : javac

If java is not installed, then you will see message:

javac is not recognized as internal or external command, operable program or batch file.

  1. Write in cmd : set path=C:\Program Files\Java\jdk1.8.0_121\bin
  2. Write in cmd : javac

You can check that path is set if not error has been raised.

It is important to note that these changes are only temporary from programs launched from this cmd.

NOTE: You might have to run the command line as admin

B. Permanent

  1. Righ-click on «My computer» and click on properties
  2. Click on «Advanced system settings»
  3. Click on «Environment variables»
  4. Click on new tab of user variable
  5. Write path in variable name
  6. Copy the path of bin folder
  7. Paste the path of the bin folder in the variable value
  8. Click OK

The path is now set permanently.

TIP: The tool «Rapid Environment Editor» (freeware) is great for modifying the environment variables and useful in that case

TIP2: There is also a faster way to access the Environment Variables: press Win+R keys, paste the following %windir%\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables and press ENTER

Jean-Francois T.'s user avatar

answered Mar 20, 2017 at 7:04

Kimmi Dhingra's user avatar

0

In Windows 7, right-click on Computer -> Properties -> Advanced system settings; then in the Advanced tab, click Environment Variables… -> System variables -> New….

Give the new system variable the name JAVA_HOME and the value C:\Program Files\Java\jdk1.7.0_79 (depending on your JDK installation path it varies).

Then select the Path system variable and click Edit…. Keep the variable name as Path, and append C:\Program Files\Java\jdk1.7.0_79\bin; or %JAVA_HOME%\bin; (both mean the same) to the variable value.

Once you are done with above changes, try below steps. If you don’t see similar results, restart the computer and try again. If it still doesn’t work you may need to reinstall JDK.

Open a Windows command prompt (Windows key + R -> enter cmd -> OK), and check the following:

java -version

You will see something like this:

java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

Then check the following:

javac -version

You will see something like this:

javac 1.7.0_79

answered Nov 4, 2015 at 3:43

Arun's user avatar

ArunArun

2,3125 gold badges24 silver badges33 bronze badges

The JDK installation instructions explain exactly how to set the PATH, for different versions of Windows.

Normally you should not set the CLASSPATH environment variable. If you leave it unset, Java will look in the current directory to find classes. You can use the -cp or -classpath command line switch with java or javac.

answered Nov 4, 2009 at 8:26

Jesper's user avatar

JesperJesper

203k46 gold badges318 silver badges350 bronze badges

1

I am going to explain here by pictures for Windows 7.

Please follow the following steps:

Step 1:
Go to «Start» and get into the «My Computer» properties

enter image description here

Step 2: Go to «Advance System Setting» and click on it.

enter image description here

Step 3: Go to «Start» and get into the «My Computer» properties

enter image description here

Step 4: The dialog for Environment variable will open like this:

enter image description here

Step 5: Go to path and click on edit.

enter image description here

Step 6: Put the path of your JDK wherever it resides up to bin like you can see in the picture. Also add path from your sdk of Android up to the Platform Tools:

enter image description here

answered Jul 10, 2015 at 12:10

hitesh141's user avatar

hitesh141hitesh141

93312 silver badges25 bronze badges

In programming context you can execute SET command (SET classpath=c:\java) or Right click on your computer > properties > advanced > environment variables.

In a batch file you can use

SET classpath=c:\java
java c:\myapplication.class

answered Nov 4, 2009 at 8:03

Cem Kalyoncu's user avatar

Cem KalyoncuCem Kalyoncu

14.2k4 gold badges41 silver badges62 bronze badges

1

For Windows 7 users:

Right-click on My Computer, select Properties; Advanced; System Settings; Advanced; Environment Variables. Then find PATH in the second box and set the variable like in the picture below.

PATH variable editor

Victor Zamanian's user avatar

answered May 26, 2014 at 7:56

Zar E Ahmer's user avatar

Zar E AhmerZar E Ahmer

34k20 gold badges236 silver badges300 bronze badges

Java path set for java 11

  1. copy the path for jdk-11

Don’t include the \bin folder, just the JDK path. For example

CorrectC:\Program Files\Java\jdk-11

WrongC:\Program Files\Java\jdk-11\bin

In environmental variable, user variable section click on New button and give path like below.
enter image description here

after that give ok for it and go to the System variables and select the Path and double click on it.

enter image description here

click on new and paste %JAVA_HOME%\bin and click ok to all.
enter image description here

answered May 6, 2021 at 22:10

Supun Sandaruwan's user avatar

Set java Environment variable in Centos / Linux

/home/ vi .bashrc

export JAVA_HOME=/opt/oracle/product/java/jdk1.8.0_45

export PATH=$JAVA_HOME/bin:$PATH

java -version

answered Aug 9, 2016 at 4:42

Guna Sekaran's user avatar

0

Keep in mind that the %CLASSPATH% environment variable is ignored when you use java/javac in combination with one of the -cp, -classpath or -jar arguments. It is also ignored in an IDE like Netbeans/Eclipse/IntelliJ/etc. It is only been used when you use java/javac without any of the above mentioned arguments.

In case of JAR files, the classpath is to be defined as class-path entry in the manifest.mf file. It can be defined semicolon separated and relative to the JAR file’s root.

In case of an IDE, you have the so-called ‘build path’ which is basically the classpath which is used at both compiletime and runtime. To add external libraries you usually drop the JAR file in a (either precreated by IDE or custom created) lib folder of the project which is added to the project’s build path.

Vishal Yadav's user avatar

Vishal Yadav

3,6423 gold badges25 silver badges42 bronze badges

answered Nov 4, 2009 at 11:54

BalusC's user avatar

BalusCBalusC

1.1m373 gold badges3613 silver badges3557 bronze badges

2

  1. Download the JDK
  2. Install it
  3. Then Setup environment variables like this :
  4. Click on EDIT

enter image description here

  1. Then click PATH, Click Add , Then Add it like this:
    enter image description here

answered May 16, 2019 at 11:04

Abhishek Sengupta's user avatar

For deployment better to set up classpath exactly and keep environment clear.
Or at *.bat (the same for linux, but with correct variables symbols):

CLASSPATH="c:\lib;d:\temp\test.jar;<long classpath>"
CLASSPATH=%CLASSPATH%;"<another_logical_droup_of_classpath" 
java -cp %CLASSPATH% com.test.MainCLass

Or at command line or *.bat (for *.sh too) if classpath id not very long:

java -cp "c:\lib;d:\temp\test.jar;<short classpath>"

answered Nov 4, 2009 at 8:26

St.Shadow's user avatar

St.ShadowSt.Shadow

1,8501 gold badge12 silver badges16 bronze badges

For Windows:

  • Right click on ‘My Computers’ and open ‘Properties’.
  • In Windows Vista or Windows 7, go to «Advanced System Settings». Else go to next step.
  • Go to ‘Advanced Tab’ and click on Environment Variables button.
  • Select ‘Path’ under the list of ‘System Variables’, and press Edit and add C:\Program Files\java\jdk\bin after a semicolon.
  • Now click on ‘new’ button under system variables and enter ‘JAVA_HOME’ as variable name and path to jdk home directory (ex. ‘C:\Program Files\Java\jdk1.6.0_24’ if you are installing java version 6. Directory name may change with diff. java versions) as variable_value.

answered Sep 6, 2013 at 11:14

Pratap Singh's user avatar

Pratap SinghPratap Singh

4,6171 gold badge22 silver badges24 bronze badges

Your Keytools file sit under «Java/bin» folder so you need to either set Environment variable or go to «Java/bin» folder and run command

answered Aug 9, 2021 at 17:35

vaquar khan's user avatar

vaquar khanvaquar khan

10.9k5 gold badges73 silver badges96 bronze badges

You can add JAVA_HOME in the system environment variable from my computer>>advance tab>add the new path as explained here.

It might help Mac and Linux users as well.

answered Jun 12, 2022 at 5:14

Sunil's user avatar

SunilSunil

3,2193 gold badges21 silver badges21 bronze badges

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

Шаг 1: Скачать установочный файл с сайта

На сегодня местонахождения файлов для скачивания 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 — поэтому буду демонстрировать на ней. В меню «Пуск» найдите пункт «Компьютер» и щелкните на нем правой кнопкой мыши. В появившемся меню выберите пункт «Свойства». Появится окно

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

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

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

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

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

В терминологии 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.

Содержание

  1. Настройка JAVA_HOME в Windows 10
  2. Установите переменную среды JAVA_HOME и обновите системный путь
  3. Проверьте настройки конфигурации JAVA_HOME, используя CMD

Настройка 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 не распознается как внутренняя или внешняя команда. Это означает, что переменная пути установлена ​​неправильно.

Надеюсь, это поможет!

I got a new laptop with Windows 10 and I want to set it up so I can use java and javac from the command line.

I have searched online but all the guides are for previous versions, and I don’t want to mess around with something I don’t understand.

General Grievance's user avatar

asked Aug 27, 2015 at 5:13

kilmarta's user avatar

0

Just set the path variable to JDK bin in environment variables.

Variable Name : PATH 
Variable Value : C:\Program Files\Java\jdk1.8.0_31\bin

But the best practice is to set JAVA_HOME and PATH as follow.

Variable Name : JAVA_HOME
Variable Value : C:\Program Files\Java\jdk1.8.0_31

Variable Name : PATH 
Variable Value : %JAVA_HOME%\bin

answered Aug 27, 2015 at 5:31

isurujay's user avatar

isurujayisurujay

1,38610 silver badges15 bronze badges

3

Here are the typical steps to set JAVA_HOME on Windows 10.

  1. Search for Advanced System Settings in your windows Search box. Click on Advanced System Settings.
  2. Click on Environment variables button: Environment Variables popup will open.
  3. Goto system variables session, and click on New button to create new variable (HOME_PATH), then New System Variables popup will open.
  4. Give Variable Name: JAVA_HOME, and Variable value : Your Java SDK home path. Ex: C:\Program Files\java\jdk1.8.0_151 Note: It should not include \bin. Then click on OK button.
  5. Now you are able to see your JAVA_HOME in system variables list. (If you are not able to, try doing it again.)
  6. Select Path (from system variables list) and click on Edit button, A new pop will opens (Edit Environment Variables). It was introduced in windows 10.
  7. Click on New button and give %JAVA_HOME%\bin at highlighted field and click Ok button.

You can find complete tutorials on my blog :

How to set JAVA_HOME in 64 bit Windows 10 OS

Monish Saravana 's user avatar

answered Dec 20, 2017 at 8:51

Chandra Shekhar Goka's user avatar

0

  • Right click Computer
  • Click the properties
  • On the left pane select Advanced System Settings
  • Select Environment Variables
  • Under the System Variables, Select PATH and click edit,
    and then click new and add path as C:\Program
    Files\Java\jdk1.8.0_131\bin
    (depending on your installation path)
    and finally click ok
  • Next restart your command prompt and open it and try javac

answered Jun 7, 2017 at 7:40

Navin prasad's user avatar

Navin prasadNavin prasad

5681 gold badge8 silver badges18 bronze badges

0

To find the env vars dialog in Windows 10:

Right Click Start
>>  Click Control Panel  (Or you may have System in the list)
>>  Click System
>>  Click Advanced system settings
>>  Go to the Advanced Tab
>>  Click the "Environment Variables..." button at the bottom of that dialog page.

answered Mar 24, 2016 at 10:31

theINtoy's user avatar

theINtoytheINtoy

3,3982 gold badges37 silver badges60 bronze badges

1

Its still the same concept, you’ll need to setup path variable so that windows is aware of the java executable and u can run it from command prompt conveniently

Details from the java’s own page: https://java.com/en/download/help/path.xml
That article applies to: •Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 8, Windows 7, Vista, Windows XP, Windows 10

answered Aug 27, 2015 at 5:21

whitecoffee's user avatar

2

if you have any version problems (javac -version=15.0.1, java -version=1.8.0)
windows search : edit environment variables for your account
then delete these in your windows Environment variable: system variable: Path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files\Common Files\Oracle\Java\javapath

then if you’re using java 15
environment variable: system variable : Path
add path C:\Program Files\Java\jdk-15.0.1\bin
is enough

if you’re using java 8

  • create JAVA_HOME
  • environment variable: system variable : JAVA_HOME
    JAVA_HOME = C:\Program Files\Java\jdk1.8.0_271

  • environment variable: system variable : Path
    add path = %JAVA_HOME%\bin
  • answered Nov 27, 2020 at 8:27

    tharsikan's user avatar

    1

  • Настройка питания usb windows 10
  • Настройка полноэкранного режима windows 10
  • Настройка параметров конфиденциальности windows 10 при установке
  • Настройка пин кода в windows 10 как пропустить
  • Настройка политики доставки windows 10