Как установить java 11
For any text in this document that contains the following notation, you must substitute the appropriate update version number:
For example, if you are downloading the JDK installer for 64-bit systems for update 11 Interim 0, Update 0, and Patch 0, then the file name jdk- 11 . interim.update.patch _windows-x64_bin.exe becomes jdk- 11 _windows-x64_bin.exe .
JDK Installation Instructions for Windows
You run a self-installing executable file to unpack and install the JDK on Windows computers.
Install JDK on Windows computers by performing the actions described in the following topics:
Downloading the JDK Installer
Access Java SE Downloads page and click Accept License Agreement . Under the Download menu, click the Download link that corresponds to the .exe for your version of Windows.
Download the file jdk- 11 . interim.update.patch _windows-x64_bin.exe .
Verify the successful completion of file download by comparing the file size on the download page and your local drive. Alternatively, you can ensure that the downloaded file’s checksum matches the one provided on the Java SE Downloads page.
Running the JDK Installer
- Start the JDK 11 installer by double-clicking the installer’s icon or file name in the download location.
- Follow the instructions provided by the installer.
- After the installation is complete, delete the downloaded file to recover the disk space.
During installation, the following files are copied to the location mentioned:
Alternatively, you can run these executables directly from the JDK’s bin directory.
Installing the JDK Silently
Instead of double-clicking or opening the JDK installer, you can perform a silent, non interactive, JDK installation by using command-line arguments.
The notation jdk stands for the downloaded installer file base name, such as jdk- 11 _windows-x64_bin.exe .
Beginning to Use the JDK
Use the Java Development Kit in the Windows Start menu to access information related to Reference Documentation.
During JDK install, Java menu items are added to the Windows Start menu to provide easy access to Reference Documentation, which is online documentation web page.
During JDK installation and uninstallation processes, the appropriate start menu items are updated so that they are associated with the latest JDK version on the system
The Windows 7 and Windows 10 have a Start menu; however, the menu is not available in Windows 8 and Windows 8.1. The JDK and Java information in Windows 8 and Windows 8.1 is available in the following Start directory: %ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs .
Uninstalling the JDK on Windows
Uninstalling the JDK in Silent Mode
You can use the command line for uninstalling the JDK.
For example, to uninstall JDK 11, run the command:
- This command can be run from anywhere.
- The msiexec.exe executable is located in the windows system directory.
- A reboot is required only if some files are in use during uninstallation; it is not necessary everytime. However, to manually suppress reboot while uninstalling, append REBOOT=R option to the command.
- Append /l “C:\< path >setup.log” option to the command if you want to create a log file describing the uninstallation status.
Windows Installer dialog appears prompting you for confirmation. Click Yes to uninstall JDK.
Finding the JDK Registry Key and UninstallString Value
- Go to Start and type Regedit .
- In the Registry Editor, go to HKEY_LOCAL_MACHINE/Software/Microsoft/Windows/CurrentVersion/Uninstall .
Under the Uninstall folder, you will find many registry entries within curly brackets.
Highlight Uninstall folder before performing search for a particular registry.
The registry key is highlighted on the right-hand side of the pane and values of various uninstall strings are displayed on the left-hand pane.
JDK Installation Troubleshooting
The following sections provide tips for resolving issues, if any, while installing JDK.
System Error During Decompression
If you see the error message: system error during decompression , then there might not be enough space on the disk that contains the TEMP directory.
Program Cannot Be Run in DOS Mode
If you see the error message: This program cannot be run in DOS mode , then do the following:
Open the MS-DOS shell or command prompt window.
Right-click the title bar.
Select the Program tab.
Ensure that the item Prevent MS-DOS-based programs from detecting Windows is not selected.
Select OK again.
Exit the MS-DOS shell.
Restart your computer.
Characters That Are Not Part of the System Code Page
A 1722 error may occur if the installation directory is not part of the system locale’s code page. To prevent this, ensure that the user and system locales are identical, and that the installation path contains only characters that are part of the system locale’s code page. User and system locales can be set in the Regional Options or Regional Settings control panel.
The associated bug number is 4895647.
Cleanup the Registry After a Failed JDK Uninstall
Sometimes, attempts to uninstall JDK through the Windows Add/Remove program leave behind some Java entries in the registry that are not fully removed. These left behind registry entries can cause problems in installing a new version of Java. The following are the methods to cleanup registry entries:
- Program Install and Uninstall troubleshooter (Recommended Method)
- Manual Registry Edit
Program Install and Uninstall troubleshooter (Recommended Method)
Run the Program Install and Uninstall troubleshooter to repair the corrupted registry keys that prevent programs from being completely uninstalled, or blocks new installations and updates.
Manually edit the registry (Use this only if the Fix It utility does not work)
Incorrectly editing your registry may severely damage your system. You should back up any valued data from your computer before making changes to the registry.
Use the File->Export functionality of the registry editor to save the registry key before deleting. In case you deleted the wrong registry key, you can restore the registry from your saved backup file, by using the File->Import functionality.
Using Red Hat OpenJDK 11 on Windows
OpenJDK (Open Java Development Kit) is a free and open-source implementation of the Java Platform, Standard Edition (Java SE).
OpenJDK 11 for Windows provides a distribution of OpenJDK that follows the Red Hat Enterprise Linux distribution of OpenJDK as closely as possible on the Microsoft Windows platform. Windows builds use Red Hat Enterprise Linux RPM sources and apply all of the relevant RPM patches.
OpenJDK 11 for Windows includes OpenJDK, fonts, timezone data, and CA certificates from Red Hat Enterprise Linux.
1. Installing OpenJDK on Windows
1.1. Installing OpenJDK using the zip bundle
The easiest way to install the JDK on Windows is to unarchive the zip via the command prompt.
Extracting the contents of the zip bundle to a directory path that does not contain spaces is recommended.
This is important as many scripts that reference the JAVA_HOME environment variable may not extract the path correctly if their is a space present.
Download the zip bundle of OpenJDK 11 for Windows.
Extract the contents of the zip bundle to a directory of your choice. See the note and caution above about spaces in the install path.
Update the PATH as below:
The above command only works if you start the command prompt with Run as administrator .
/m updates the value as a system wide setting, instead of the default local environment.
You have to restart the command prompt to check the setting by typing path .
Verify the OpenJDK 11 for Windows is installed by running: java -version in a newly opened command prompt and you should see the following:
The %JAVA_HOME% environment variable must also be set to use some developer tools.
Set the %JAVA_HOME% environment variable as
JAVA_HOME will not work if the bin directory is appended to your installation path.
After restarting the command prompt, you can view your setting by typing echo %JAVA_HOME% .
Open Command Prompt as an administrator.
Set the value of the environment variable to your OpenJDK installation path:
If the path contains spaces, use the shortened path name.
Restart Command Prompt to reload the environment variables.
1.2. Installing OpenJDK with the MSI Installer
The simplest way to install OpenJDK on Microsoft Windows.
Run the installer for OpenJDK 11 for Windows.
Click Next on the Welcome Screen
Check I accept the terms in the License Agreement , then click Next
Click Next and accept the defaults, review the optional properties below if you wish to make changes.
Click Yes on, «Do you want to allow this app to make changes to your device?».
Verify the OpenJDK 11 for Windows is installed by running: java -version in a newly opened Command Prompt and you should see the following:
Select the desired extra environment settings if needed as described below
The OpenJDK 11 for Windows MSI-based installer includes the following components and sets the following properties:
Components
Java Development Kit (JDK) OpenJDK 11 for Windows files.
Properties
OpenJDK Runtime — Windows Registry
The following registry keys are set HKLM\Software\JavaSoft\JDK\<version>, entries: JavaHome: <INSTALLDIR> RuntimeLib: <INSTALLDIR>\bin\server\jvm.dll
HKLM\Software\JavaSoft\JDK, entries: CurrentVersion: <version>
OpenJDK Runtime — Path Variable
Adds the Runtime to the Path variable so it is available from the command line.
OpenJDK Runtime — JAVA_HOME System Variable
JAVA_HOME is used by some programs to find the Java runtime.
OpenJDK Runtime — REDHAT_JAVA_HOME System Variable
REDHAT_JAVA_HOME will be used in the future for Mission Control.
OpenJDK Runtime — Jar Files Association
This enables Jar files to be run from within Windows Explorer.
Web Start (Beta) — JNLP File Association
Enables the launching of JNLP files downloaded from the web.
Web Start (Beta) — PATH Variable
Enables the launching of JNLP files downloaded from the web from the local file system.
Web Start (Beta) — Keep Settings and Cache
Keeps settings and caches on the local file system.
Mission Control — Path Variable
Adds Mission Control to the Path Variable so it is available from the command line.
2. Updating OpenJDK on Windows
2.1. Updating OpenJDK for Microsoft Windows using the zip bundle
OpenJDK 11 for Windows can be manually update using the zip bundle.
Extract the contents of the ZIP bundle to a directory of your choice.
Extracting the contents of the zip bundle to a directory path that does not contain spaces is recommended.
On the command prompt, update JAVA_HOME environment variable as follows:
Open Command Prompt as an administrator.
Set the value of the environment variable to your OpenJDK installation path:
Установка Java в Ubuntu 20.04
Java — это очень популярный язык программирования, разработанный в компании Sun Microsystems, ныне принадлежащая корпорации Oracle. Сейчас Java используется для создания различных прикладных программ, веб-приложений, серверных приложений и многого другого. Основная особенность этого языка — это максимальная кроссплатформенность.
Программа, написанная для одной системы, будет без проблем работать в другой. Но для программ, написанных на Java, нужна специальная виртуальная Java-машина. В этой статье будет рассмотрена установка Java в Ubuntu 20.04 для разных версий программы. А также попытаемся разобраться во всём её многообразии.
Какую версию Java выбрать?
Сейчас разработкой Java занимается компания Oracle. До недавнего времени существовало две основных версии виртуальной машины Java:
- Старая седьмая версия;
- Новая восьмая, используемая в большинстве программ.
Платформа распространялась в двух форматах:
- Проприетарном (Oracle Java) — с дополнительными возможностями и поддержкой;
- Открытом (Open JDK) — полностью открытая версия.
Обе платформы выпускались компанией Oracle, но вторая поддерживалась сообществом разработчиков, а первая самой компанией. Сейчас же ситуация немного изменилась. Теперь компания выпускает новую версию Java каждые полгода. Сначала вышли версии Java 9, 10, 11, 12, 13, 14, 15, 16 и на конец последней актуальной версией на октябрь 2021 года является 17 версия. Длительность срока поддержки этих версий тоже короткая — всего семь месяцев. Поэтому большинство программ остались работать на Java 8 и на Java 11 так как данные версии имеют выпуск LTS – то есть Long Term Support (долгосрочная поддержка) и будут поддерживаться вплоть до Декабря 2030 года (версия Java 8) и до Сентября 2026 года. В большинстве случаев именно эти версии и необходимо устанавливать.
Если вы разработчик, и хотите получить самую свежую версию Java, то стоит устанавливать Java 11. Это LTS-версия, которая будет поддерживаться до 2026 года. В ней было очень много улучшений и изменений, как в плане синтаксиса, так и для распространения. Теперь проприетарная версия доступна бесплатно только для некоммерческого использования. Для коммерческих целей необходимо заплатить или же устанавливать OpenJDK.
В Ubuntu и в других дистрибутивах Java поставляется в двух редакциях:
- JDK или Java Development Kit — содержит полную версию Java, необходимую для разработки на этом языке;
- JRE или Java Runtime Environment — содержит только окружение для выполнения программ.
Выбор остается полностью за пользователем. Если нет необходимости что-то компилировать на Java, то будет достаточно установки JRE. Далее будет рассмотрена установка Java.
Установка Java 8 в Ubuntu 20.04
1. Как установить OpenJDK в Ubuntu 20.04
Если необходимо установить OpenJDK в Ubuntu, то никаких сторонних репозиториев подключать не нужно. Восьмая версия платформы есть в официальном репозитории Ubuntu 20.04. Чтобы установить JDK на Ubuntu необходимо выполнить команду:
sudo apt -y install openjdk-8-jdk

Для установки JRE в Ubuntu необходимо выполнить команду
sudo apt -y install openjdk-8-jre

После этого можно узнать версию Java:

Версия 1.8.0 эквивалентна версии 8.
2. Как установить Oracle Java 8 в Ubuntu 20.04
Единственный рабочий способ получить самую свежую версию Java — скачать её из официального сайта. Необходимо выбрать раздел Linux и найти пакет с именем jdk-8u311-linux-aarch64.tar.gz:

Далее необходимо поставить галочку напротив пункта I reviewed and accept the Oracle Technology Network License Agreement for Oracle Java SE тем самым подтверждая принятия условия лицензионного соглашения.

Для скачивания файла необходимо войти в свою учетную запись Oracle или создать новую, только после этого начнется загрузка выбранной версии. После завершения загрузки необходимо создать директорию /usr/lib/jvm/:
sudo mkdir /usr/lib/jvm/
Распакуйте в неё скаченный ранее архив:
sudo tar -zxvf jdk-8u311-linux-aarch64.tar.gz -C /usr/lib/jvm/
Добавьте исполняемый файл Java к списку утилиты для управления версиями Java:
sudo update-alternatives —install /usr/bin/java java /usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java
После этого активируйте данную версию:
sudo update-alternatives —config java

Введите цифру 1 для выбора версии Java. В данном случае будет выбрана ранее скачанная версия Oracle Java 8.
Некоторым приложениям необходим путь к исполняемым файлам Java в переменных окружения. Создайте файл /etc/profile.d/javajdk.sh:
sudo vi /etc/profile.d/java8jdk.sh
И впишите следующее содержимое:
export PATH=$PATH:/usr/lib/jvm/jdk1.8.0_311/bin export JAVA_HOME=/usr/lib/jvm/jdk1.8.0_311 export JRE_HOME=/usr/lib/jvm/jdk1.8.0_311/jre export J2SDKDIR=/usr/lib/jvm/jdk1.8.0_311/ export J2REDIR=/usr/lib/jvm/jdk1.8.0_311/jre/
Чтобы загрузить эти переменные необходимо выполнить команду:
После этого проверьте версию Java:

Установка Java 11 в Ubuntu 20.04
1. Как установить OpenJDK 11 в Ubuntu 20.04
Java 11 — это последняя на данный момент версия Java c длительной и актуальной поддержкой. Она будет поддерживаться до 2026 года. Свободная версия есть в официальных репозиториях Ubuntu, поэтому установить её можно без проблем:
sudo apt -y install openjdk-11-jdk

Или можно установить JRE-редакцию, предназначенную только для запуска программ:
sudo apt -y install openjdk-11-jre

После установки необходимо переключиться на 11 версию. Для этого выполните команду:
sudo update-alternatives —config java
Введите необходимую цифру для выбора Java 11. В данном случае будет выбрана цифра 0:

После этого проверьте версию Java:

2. Как установить Oracle Java 11 в Ubuntu 20.04
Для установки проприетарной версии Java от корпорации Oracle необходимо скачать пакет JDK с официального сайта Oracle и добавить репозиторий для установки Java. Если просто попытаться выполнить команду для установки минуя скачивание JDK apt выдаст ошибку Oracle JDK 11 is NOT installed.
Для начала необходимо скачать архив с JDK с официального сайта Oracle . Необходимо выбрать раздел Linux и найти пакет с именем jdk-11.0.13_linux-x64_bin.tar.gz:

Далее необходимо поставить галочку напротив пункта I reviewed and accept the Oracle Technology Network License Agreement for Oracle Java SE тем самым подтверждая принятия условия лицензионного соглашения. Для скачивания файла необходимо войти в свою учетную запись Oracle или создать новую, только после этого начнется загрузка архива.
Необходимо создать директорию / var / cache / oracle — jdk 11- installer — local / и скопировать туда скачанный архив:
sudo mkdir -p /var/cache/oracle-jdk11-installer-local/
sudo cp /home/alex/Downloads/jdk-11.0.13_linux-x64_bin.tar.gz /var/cache/oracle-jdk11-installer-local/

Далее необходимо добавить репозиторий:
sudo add-apt-repository ppa:linuxuprising/java

При появлении фразы Press [ENTER] to continue or Ctrl-c to cancel adding it. нажмите на клавишу Enter для продолжения установки репозитория. Далее установите Oracle Java 11 при помощи команды:
sudo apt -y install oracle-java11-set-default-local
При появлении окна с лицензией нажмите на клавишу Tab далее нажмите на клавишу Enter:

В следующем окне снова нажмите на клавишу Tab и на клавишу Enter:

После этого проверьте версию Java:

Выбор версии Java
Если в системе установлено несколько версий Java, необходимо выбрать, какая из них будет использоваться по умолчанию. Для этого используется утилита update-java-alternatives. Для просмотра списка всех установленных версий необходимо выполнить команду:
sudo update-java-alternatives —list

Далее установите необходимую версию при помощи опции –set и задав полное имя Java:
sudo update-java-alternatives —set java-1.11.0-openjdk-amd64
Удаление Java из Ubuntu 20.04
Чтобы удалить ненужную версию Java, выполните одну из перечисленных ниже команд для удаления конкретной версии или выполните все команды поочередно для удаления всех версий Java:
sudo apt -y purge oracle-java11-installer sudo apt purge openjdk-11* sudo apt purge openjdk-8*
Далее можно удалить PPA-репозиторий:
sudo add-apt-repository —remove ppa:linuxuprising/java
Выводы
В этой статье была показана установка Java на Ubuntu 20.04. Теперь после прочтения данной статьи вы знаете, как устанавливать Java и как выбирать необходимую версию по умолчанию. Надеюсь, информация из статьи была вам полезной.
Установка JDK в Windows
В этой статье мы установим JDK 11 на Windows. Java Development Kit (JDK) – это набор программ и библиотек для разработки программ на Java. Если вы хотите разрабатывать на Java программы, сперва вам нужно установить актуальную версию JDK.
В данной статье мы покажем, как установить JDK 11. Эта версия LTS (long time support), которая будет поддерживаться до сентября 2022 года. Вы можете установить любую другую версию JDK на ваш вкус, используя эту инструкцию.
Как установить JDK
Скачайте нужный дистрибутив JDK
Зайдите на страницу загрузки JDK и нажмите JDK Download

На следующей страницу выберите дистрибутив «Windows x64 Installer»:

Появится всплывающее окно. Согласитесь с условиями лицензии и нажмите кнопку Download:

Для скачивания вам потребуется залогиниться в существующую учётную запись Oracle. Если у вас её нет, вы можете создать новую учётную запись.
Если вам лень заморачиваться с созданием учётных записей, найдите работающий логин/пароль на сайте bugmenot


Начнётся скачивание инсталлятора. По окончанию загрузки запустите установку:

На этапе выбора компонентов укажите путь установки. Я крайне рекомендую вам заменить стандартный путь C:\Program Files путём, не содержащих пробелов, например, C:\Java\jdk-11

Через несколько минут установка завершится:

Для проверки вы можете зайти в указанный вами путь и проверить, что там есть следующий контент:

Настройка переменных окружения
После успешной установки JDK, крайне желательно объявить переменную окружения JAVA_HOME. Эта переменная используется многими программами и инструментами из стандартного набора Java разработчика.
Для этого откройте окно «Этот компьютер» → «Свойства»:

Затем откройте окно «Дополнительные параметры системы» и в нём нажмите кнопку «Переменные среды…»

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

В появившемся окне введите следующие значения:
Имя переменной: JAVA_HOME
Значение переменной: <тот путь, который вы указали при установке>

Затем найдите системную переменную Path и измените её:

Нажмите кнопку «Создать», и укажите в новой строке значение %JAVA_HOME%\bin

Также, если вы видите в этом списке путь к программе javapath (как на скриншоте), удалите его.
Проверка установки
После установки переменных окружения откройте консоль (Win+R, cmd)


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

Если вы видите вывод наподобие этого, значит, вы корректно установили JDK и правильно указали переменные окружения. Вы готовы написать свою программу на Java!
Резюме
В данном уроке мы научились устанавливать JDK и настраивать перменные окружения. В следующих уроках мы установим основные инструменты Java программиста.