- . как установить Java на Windows?
- 1. Где взять Java?
- 2. Какую версию выбрать?
- 3. Что устанавливать, JRE или JDK?
- 4. Установка Java
- 5. Настройка переменных окружения
- 6. Удаление лишних файлов
- Автор: Алексей Баранцев
- How To Set Java, JRE and JDK Home Path and Environment Variables On Windows?
- Locate JRE or JDK Path
- Set Java HOME_PATH Environment Variable
- Set JAVA Executable Path
- Check Java Is Working
- 3 thoughts on “How To Set Java, JRE and JDK Home Path and Environment Variables On Windows?”
- PATH and CLASSPATH
- Update the PATH Environment Variable (Microsoft Windows)
- Update the PATH Variable (Solaris and Linux)
- Checking the CLASSPATH variable (All platforms)
. как установить Java на Windows?
Эта инструкция устарела, используйте вместо неё более новую
Во многих моих тренингах так или иначе используется Java, либо как язык программирования для разработки автотестов, либо как виртуальная машина для запуска приложений, написанных на Java — инструментов тестирования, сред разработки, и даже клиент системы видеоконференций GotoWebinar требует наличия Java.
Поэтому я решил описать процедуру установки Java для операционной системы Windows и последующей настройки системы, потому что, к сожалению, недостаточно просто “запустить инсталлятор и всегда нажимать кнопку Next”.
1. Где взять Java?
2. Какую версию выбрать?
Разумеется, последнюю доступную (на момент написания инструкции это Java 8).
Выбирая из 32-битной и 64-битной версий, берите 64-битную, если ваша операционная система это позволяет, потому что у неё менее строгие ограничения по памяти, доступной исполняемым Java-приложениям.
3. Что устанавливать, JRE или JDK?
Java Runtime Environment, или JRE — это виртуальная машина, позволяющая запускать приложения, написанные на языке программирования Java.
Java Development Kit, или JDK — это набор инструментов, для разработки программ на языке программирования Java (компилятор, архиватор, генератор документации и прочие). JRE разумеется тоже входит в дистрибутив JDK.
Правило очень простое: если вы собираетесь что-нибудь писать на языке программирования Java, значит вам потребуется JDK. А если только запускать готовые программы — тогда достаточно JRE.
4. Установка Java
Вот тут, действительно, всё просто — нужно запустить инсталлятор и следовать указаниям визарда. Можно просто всё время нажимать кнопку Next.
5. Настройка переменных окружения
К сожалению, инсталлятор Java не выполняет настройку переменных окружения, поэтому придётся сделать это вручную после установки.
Во-первых, необходимо установить переменную JAVA_HOME , которая должна указывать на директорию, в которую установлена Java. Многие программы используют эту переменную, чтобы определить, где находится Java.
Во-вторых, надо в переменную PATH добавить путь к директории %JAVA_HOME%\bin . Эта переменная указывает операционной системе список директорий, в которых нужно искать исполняемые файлы, и чтобы можно было запускать Java из консоли, переменная PATH должна быть правильно настроена.
Для установки переменных окружения сначала нужно открыть свойства компьютера, либо использовав сочетание клавиш Win-Pause, либо через меню “Пуск”:
Затем нужно выбрать “Дополнительные параметры системы”, в открывшемся диалоге перейти на вкладку “Дополнительно” и нажать кнопку “Переменные среды”, после чего появится диалог настройки переменных окружения.
Если у вас уже есть переменная окружения JAVA_HOME — надо её отредактировать, если нет — создать новую. В качестве значения нужно указать путь к директории, куда установлена Java, то есть, например c:\Program Files\Java\jdk1.8.0_25\ , если вы установили JDK, либо c:\Program Files\Java\jre1.8.0_25\ , если вы установили только JRE.
После того, как вы установили значение переменной JAVA_HOME , необходимо отредактировать значение переменной PATH, добавив туда путь к директории, где находятся исполняемые файлы Java, то есть %JAVA_HOME%\bin
И сохранить всё это, закрыв все открытые диалоги в обратном порядке кнопками OK.
Обратите внимание, что если вы устанавливаете JDK, то в названии директории указывается номер версии, поэтому впоследствии, когда вы решите установить более новую версию, не забудьте поменять значение переменной окружения JAVA_HOME .
После того, как вы изменили переменные окружения, новые значения будут действительны только для новых запускаемых программ, уже запущенные программы не узнают о том, что переменные окружения поменялись. Поэтому если вы, например, пытались запустить Java из консоли и у вас не получилось из-за неправильных настроек переменной PATH , вам придётся перезапустить консоль после того, как вы поменяли значение переменной.
6. Удаление лишних файлов
Запустите консоль ( cmd ) и выполните в ней команду where java .
В результате вы должны увидеть путь к исполняемому файлу java.exe , который операционная система должна успешно обнаружить в том месте, куда вы установили Java. Если файл не нашёлся — значит неправильно настроена переменная PATH и нужно вернуться к предыдущему пункту.
Однако иногда бывает и наоборот, находятся «лишние» исполняемые файлы:
Происходит это из-за того, что инсталлятор Java вместо того, чтобы правильно настроить переменные окружения, пытается положить исполняемые файлы в директорию C:\Windows\system32
Это не очень хорошо — засоряется системная директория, может возникнуть рассогласование версий Java (в разных директориях разные версии). Поэтому надо удалить из каталога C:\Windows\system32 исполняемые файлы java.exe , javaw.exe и javaws.exe , если они там обнаружатся.
Вот и всё, теперь можно пользоваться Java. Только не забывайте о том, что после установки новой версии надо будет обновить переменную окружения JAVA_HOME !
Автор: Алексей Баранцев
Если вам понравилась эта статья, вы можете поделиться ею в социальных сетях (кнопочки ниже), а потом вернуться на главную страницу блога и почитать другие мои статьи.
Ну а если вы не согласны с чем-то или хотите что-нибудь дополнить – оставьте комментарий ниже, может быть это послужит поводом для написания новой интересной статьи.
How To Set Java, JRE and JDK Home Path and Environment Variables On Windows?
Java is a very popular programming language which provides a different component in order to run, develop Java applications. JRE or Java Runtime Environment is used to run Java application. JDK or Java Development Kit is used to develop Java applications. In this tutorial, we will learn how to set up Java, JRE, and JDK operating system path variables in order to work properly.
Locate JRE or JDK Path
Before starting the configuration we have to locate the JRE or JDK path. JRE or JDK generally installed on the Program Files or Program Files(x86) directory under the Java directory like below.
Locate JRE or JDK Path
and under the Java directory the JDK is residing.
Locate JRE or JDK Path
Set Java HOME_PATH Environment Variable
Now we have learned the path of the Java, JRE or JDK installation. We can set this path as Java HOME_PATH environment variable. We will open the computer properties with by running sysdm.cpl in the Run menu like below. We can also open it from the File Explorer -> Computer -> Right Click.
Open System Properties
In the system properties, we will navigate to the Advanced tab which provides the Environment Variables button like below.
Open Environment Variables
Below we can see the environment variables menu where we will create the JAVA_HOME system variable and set the path accordingly. We click to the New in order to create a new system variable.
Create New System Variable
Here we will set the Variable Name as JAVA_HOME and the Variable Value the path or Java, JRE or JDK which is C:\Program Files\Java\jdk-12 in this example. Then we will click OK.
Set JAVA Executable Path
If we want to run java.exe or similar executables provided by JRE or JDK we have to add the path of Java in the Path variable like below. We select the system variable named Path and click to the Edit .
Here we click to New which will add a new line to the existing values.
Here we will set the bin folder path which is C:\Program Files\Java\jdk-12\bin in this example.
Add Path System Variable
Then we will click OK and OK in the environment variables screen which will save and activated new path configuration.
Check Java Is Working
We can check the new path configuration simply opening a new command line interface MS-DOS. Then just type java -version which will execute java.exe with the -version option. We can see the current java binary version by running it.
3 thoughts on “How To Set Java, JRE and JDK Home Path and Environment Variables On Windows?”
What is the point in setting the JAVA_HOME to the path to the jdk install folder path if you then edit the Path variable and add the full path to the jdk bin folder? Shouldn’t you make use of the JAVA_HOME variable and add %JAVA_HOME%\bin to the Path instead.
@James Coffey, maybe the point of setting JAVA_HOME is just in preparation for GlassFish:
https://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/index.html
Still, the author could make use of it in Path as you say, but maybe the author is just trying to keep it simple.
THANK YOU SO MUCH. YOU SAVED MY LIFE. I need to use java in jupyter
PATH and CLASSPATH
This section explains how to use the PATH and CLASSPATH environment variables on Microsoft Windows, Solaris, and Linux. Consult the installation instructions included with your installation of the Java Development Kit (JDK) software bundle for current information.
After installing the software, the JDK directory will have the structure shown below.
The bin directory contains both the compiler and the launcher.
Update the PATH Environment Variable (Microsoft Windows)
You can run Java applications just fine without setting the PATH environment variable. Or, you can optionally set it as a convenience.
Set the PATH environment variable if you want to be able to conveniently run the executables ( javac.exe , java.exe , javadoc.exe , and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:
The PATH environment variable is a series of directories separated by semicolons ( ; ). Microsoft Windows looks for programs in the PATH directories in order, from left to right. You should have only one bin directory for the JDK in the path at a time (those following the first are ignored), so if one is already present, you can update that particular entry.
The following is an example of a PATH environment variable:
It is useful to set the PATH environment variable permanently so it will persist after rebooting. To make a permanent change to the PATH variable, use the System icon in the Control Panel. The precise procedure varies depending on the version of Windows:
Windows XP
- Select Start, select Control Panel. double click System, and select the Advanced tab.
- Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
- In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Windows Vista:
- From the desktop, right click the My Computer icon.
- Choose Properties from the context menu.
- Click the Advanced tab (Advanced system settings link in Vista).
- Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
- In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Windows 7:
- From the desktop, right click the Computer icon.
- Choose Properties from the context menu.
- Click the Advanced system settings link.
- Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
- In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Update the PATH Variable (Solaris and Linux)
You can run the JDK just fine without setting the PATH variable, or you can optionally set it as a convenience. However, you should set the path variable if you want to be able to run the executables ( javac , java , javadoc , and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:
To find out if the path is properly set, execute:
This will print the version of the java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set.
To set the path permanently, set the path in your startup file.
For C shell ( csh ), edit the startup file (
For bash , edit the startup file (
For ksh , the startup file is named by the environment variable, ENV . To set the path:
For sh , edit the profile file (
Then load the startup file and verify that the path is set by repeating the java command:
For C shell ( csh ):
For ksh , bash , or sh :
Checking the CLASSPATH variable (All platforms)
The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)
The preferred way to specify the class path is by using the -cp command line switch. This allows the CLASSPATH to be set individually for each application without affecting other applications. Setting the CLASSPATH can be tricky and should be performed with care.
The default value of the class path is «.», meaning that only the current directory is searched. Specifying either the CLASSPATH variable or the -cp command line switch overrides this value.
To check whether CLASSPATH is set on Microsoft Windows NT/2000/XP, execute the following:
On Solaris or Linux, execute the following:
If CLASSPATH is not set you will get a CLASSPATH: Undefined variable error (Solaris or Linux) or simply %CLASSPATH% (Microsoft Windows NT/2000/XP).
To modify the CLASSPATH , use the same procedure you used for the PATH variable.
Class path wildcards allow you to include an entire directory of .jar files in the class path without explicitly naming them individually. For more information, including an explanation of class path wildcards, and a detailed description on how to clean up the CLASSPATH environment variable, see the Setting the Class Path technical note.