How to install jdk to ubuntu
How to install jdk to ubuntu
How to install jdk to ubuntu
This topic describes the installation procedures of the JDK on the Linux platform, along with the system requirements.
General Notes About Installing the JDK on Linux Platforms
This topic describes general information about installing JDK 18 on Linux platforms.
By default, the installation script configures the system such that the backing store for system preferences is created inside the JDK installation directory as applicable. If the JDK is installed on a network-mounted drive, then the system preferences can be exported for sharing with Java runtime environments on other machines.
System Requirements for Installing JDK on Linux Platforms
See Oracle JDK Certified Systems Configurations for information about supported platforms, operating systems, and browsers.
JDK Installation Instruction Notation for Linux Platforms
Instructions for installing JDK contains a version notation that represents the Feature, Interim, and Update version information.
For example, if you are installing JDK 18 Interim 0, Update 0, and Patch 0, then the following string represents the name of the bundle:
If a component has 0 as the suffix, it will be excluded.
Installing the JDK on Linux from Archive Files and RPM Packages
You can install the Java Development Kit (JDK) on a Linux platform from archive files or from Red Hat Package Manager (RPM) packages.
Installation can be performed by using one of the following processes:
Downloading the JDK Installer
The following table lists the options and instructions for downloading and installing the JDK 18 release on a Linux platform:
Installing the 64-Bit JDK on Linux Platforms
Before you download a file, you must accept the license agreement. Anyone (not only root users) can install the archive file in any location having write access.
Installing the 64-Bit JDK on RPM-Based Linux Platforms
Before you download a file, you must accept the license agreement.
Upgrade the required package using the following command:
In addition, users can check which specific RPM package provides the java files:
How to install Java JDK on Ubuntu
By mkyong | Last updated: March 29, 2021
Viewed: 617,906 (+313 pv/w)
This tutorial shows you how to install OpenJDK 8, 11, 16, and other JDK builds on Ubuntu 20.
1. APT Install JDK (OpenJDK 8 and 11)
This example shows how to use apt install to install the OpenJDK 8 and 11 on Ubuntu.
1.1 We can use sudo apt search openjdk to find all available OpenJDK in the default repository. The below search result show four OpenJDK are available to install.
1.2 If we want to install Java 8.
1.3 If we want to install Java 11.
1.5 And the global /usr/bin/java is linked to one of the installed JDK.
2. Install JDK manually (OpenJDK 16)
If we want the latest Java JDK, for example JDK 16, early-access builds, or other JDK builds like AdoptOpenJDK, which are not available in the Ubuntu default repository. We can still download the JDK and install it on Ubuntu manually.
This example will install the JDK 16.
2.4 Update the /etc/alternatives/java link.
3. Install Oracle JDK on Ubuntu
We need to create an Oracle account to download the Oracle JDK. Please visit the official Oracle JDK link to download the JDK and follow the above install JDK manually, and it works the same.
The Oracle JDK 11 and above are paid products, and you need a license for production use. However, it’s still free to download for development and testing.
Note
In the old days, we can install the Oracle JDK in the following ways, but it failed now; please read New Oracle Java 11 Installer For Ubuntu
Install Oracle JDK 11 (Not working now)
Install Oracle JDK 8
4. Switch between different JDK versions
5. Add JAVA_HOME to Ubuntu environment variable
Many servers, frameworks, and tools depend on the JAVA_HOME environment variable to find the installed Java. On Ubuntu, we can add the JAVA_HOME to the system-wide environment variables – /etc/environment.
5.1 Open the file /etc/environment with your favorite text editors like vi, vim, or nano.
5.2 Add JAVA_HOME at a new line and point it to one of the installed JDK.
5.3 source /etc/environment to reflect the changes in the current session.
How To Install Java with Apt on Ubuntu 20.04
Introduction
Java and the JVM (Java’s virtual machine) are required for many kinds of software, including Tomcat, Jetty, Glassfish, Cassandra and Jenkins.
Prerequisites
To follow this tutorial, you will need:
Installing the Default JRE/JDK
The easiest option for installing Java is to use the version packaged with Ubuntu. By default, Ubuntu 20.04 includes Open JDK 11, which is an open-source variant of the JRE and JDK.
To install this version, first update the package index:
Next, check if Java is already installed:
If Java is not currently installed, you’ll see the following output:
Execute the following command to install the default Java Runtime Environment (JRE), which will install the JRE from OpenJDK 11:
The JRE will allow you to run almost all Java software.
Verify the installation with:
You’ll see output similar to the following:
You may need the Java Development Kit (JDK) in addition to the JRE in order to compile and run some specific Java-based software. To install the JDK, execute the following command, which will also install the JRE:
You’ll see the following output:
Next, let’s look at how to install Oracle’s official JDK and JRE.
Installing Oracle JDK 11
Oracle’s licensing agreement for Java doesn’t allow automatic installation through package managers. To install the Oracle JDK, which is the official version distributed by Oracle, you must create an Oracle account and manually download the JDK to add a new package repository for the version you’d like to use. Then you can use apt to install it with help from a third party installation script.
The version of Oracle’s JDK you’ll need to download must match version of the installer script. To find out which version you need, visit the oracle-java11-installer page.
Locate the package for Focal, as shown in the following figure:
You don’t need to download anything from this page; you’ll download the installation script through apt shortly.
Then visit the Downloads page and locate the version that matches the one you need.
You’ll be presented with a screen asking you to accept the Oracle license agreement. Select the checkbox to accept the license agreement and press the Download button. Your download will begin. You may need to log in to your Oracle account one more time before the download starts.
Once the file has downloaded, you’ll need to transfer it to your server. On your local machine, upload the file to your server. On macOS, Linux, or Windows using the Windows Subsystem for Linux, use the scp command to transfer the file to the home directory of your sammy user. The following command assumes you’ve saved the Oracle JDK file to your local machine’s Downloads folder:
Once the file upload has completed, return to your server and add the third-party repository that will help you install Oracle’s Java.
Install the software-properties-common package, which adds the add-apt-repository command to your system:
Next, import the signing key used to verify the software you’re about to install:
You’ll see this output:
Then use the add-apt-repository command to add the repo to your list of package sources:
You’ll see this message:
Update your package list to make the new software available for installation:
Finally, install the package:
The installer will first ask you to accept the Oracle license agreement. Accept the agreement, then the installer will extract the Java package and install it.
Now let’s look at how to select which version of Java you want to use.
Managing Java
You can have multiple Java installations on one server. You can configure which version is the default for use on the command line by using the update-alternatives command.
This is what the output would look like if you’ve installed both versions of Java in this tutorial:
Choose the number associated with the Java version to use it as the default, or press ENTER to leave the current settings in place.
You can do this for other Java commands, such as the compiler ( javac ):
Setting the JAVA_HOME Environment Variable
Many programs written using Java use the JAVA_HOME environment variable to determine the Java installation location.
To set this environment variable, first determine where Java is installed. Use the update-alternatives command:
This command shows each installation of Java along with its installation path:
In this case the installation paths are as follows:
Copy the path from your preferred installation. Then open /etc/environment using nano or your favorite text editor:
At the end of this file, add the following line, making sure to replace the highlighted path with your own copied path, but do not include the bin/ portion of the path:
Modifying this file will set the JAVA_HOME path for all users on your system.
Save the file and exit the editor.
Now reload this file to apply the changes to your current session:
Verify that the environment variable is set:
You’ll see the path you just set:
Other users will need to execute the command source /etc/environment or log out and log back in to apply this setting.
Conclusion
In this tutorial you installed multiple versions of Java and learned how to manage them. You can now install software which runs on Java, such as Tomcat, Jetty, Glassfish, Cassandra or Jenkins.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Ubuntu Documentation
Introduction
Java is a technology originally developed by Sun Microsystems, and acquired by Oracle. The following are the prevalent implementations:
OpenJDK: The OpenJDK project is an open-source implementation of the Java SE Platform. This is the default version of Java that is provided from a supported Ubuntu repository. Currently, there are two versions available, openjdk-6 and openjdk-7.
Oracle Java: Oracle Java is the proprietary, reference implementation for Java. This is no longer currently available in a supported Ubuntu repository. For more on this, please see here. However, one may install a supported version of Java (7 or 8) via Oracle’s website, or via the WebUpd8 PPA.
IBM Java: IBM Java is the preferred Java solution on PowerPC machines. It is a reimplementation of Java with a Just-In-Time Compiler. It is only available from IBM’s website.
GNU Compiler: A Java compiler made by GNU.
OpenJDK
Installation of Java Runtime Environment
Install the openjdk-6-jre package using any installation method.
Install the openjdk-7-jre package using any installation method.
Browser plugin
Install the icedtea6-plugin package using any installation method.
Install the icedtea-7-plugin package using any installation method.
This plugin works with the browsers: Epiphany, Firefox and Opera.
On Konqueror, go to Settings → Configure Konqueror. and from menu select Java & JavaScript, then tick Enable Java globally option.
OpenJDK v6 & v7 SDK (Software Development Kit)
In Java parlance the Java Development Kit (JDK) is sometimes used for SDK. (More about that here.)
Install the openjdk-6-jdk package using any installation method.
Install the openjdk-7-jdk package using any installation method.
Alternative Virtual Machines
Most users won’t need to worry about these, but if you use an architecture (e.g. PowerPC) that defaults to the Zero Virtual Machine (VM), then you may see a significant performance increase if you switch to:
JamVM: This is the default VM for ARM in 11.10. Install the icedtea-6-jre-jamvm package if available. If it is not, then compile instructions can be found here.
Cacao: Ensure the icedtea-6-jre-cacao package is installed.
Zero/Shark: Shark is a just-in-time (JIT) compiler for Zero. Install the openjdk-6-jre-zero package if available. On architectures which use the Zero VM as the default, the openjdk-6-jre-zero package contains the Shark VM.
To use a different VM other than the default, just add the appropriate option to the command you normally use. For example:
See the file /usr/lib/jvm/java-6-openjdk-powerpc/docs/README.Debian (or its equivalent) and the other documents in that directory for more information. Note, the IcedTea browser plugin will use the default VM (which you can change in the file /etc/java-6-openjdk/jvm.cfg).
Oracle Java 7
Installing Oracle Java 7 by a script or from the command line
You can install the newest and secure Oracle Java 7 by a script (JRE only) or by a command line method. Both are easy to apply.
Script (JRE only)
Only supports Oracle (Sun) Java 7 JRE (which covers the needs of 99 % of all computer users). It pulls the packages from Oracle’s website and installs them, comparable to the way Adobe Flash Player is being installed. Plus it adds a dedicated repository, from which you’ll receive updates automatically.
Command line methods
Do-it-yourself methods, but very easy to apply (basically: you copy/paste some terminal commands).
http://sites.google.com/site/easylinuxtipsproject/java (for JRE, more extensive explanation of the commands than in askubuntu.com)
Using webupd8.org’s method has a great benefit in that the package will be updated as Oracle releases Java updates, which means that there will be no need to keep track of updates and reinstall them manually.
A note (hopefully temporary) about the Eugene San PPA for those who are attempting to use it and are having issues: As of the time of this entry, the eugenesan/java PPA is broken. If you have attempted to use it, you may do the following to remove it and use webupd8.org’s PPA method (above) instead
If the preceding does not work, you may try the following more aggressive method. Be aware, however, that it uses the rm command, which will completely remove files immediately and permanently from an important directory. Be extremely cautious.
There is also an RFE opened on Oracle bugtracker to provide the debian package/installer for Java 7. Please consider voting for this RFE.
Oracle Java 8
Command line installation methods
Do-it-yourself method, but very easy to apply (basically: you copy/paste some terminal commands).
OpenJDK Java 8
Build it yourself
It’s actually also easy to build the Java 8 yourself directly from sources. Sounds scary? It really is surprisingly easy, and seriously literally takes about 15 minutes, using hgomez/obuildfactory, as described on vorburger.ch blog post.
OpenJDK Java 9
Build it yourself
Once you have a Java 8 bootstrap JDK, either from the binary Oracle package or one of the PPAs or one you built yourself, it’s then easy to build OpenJDK Java 9 yourself. Use the same as above, but make sure that you set the JDK_HOME and PATH to point to your Java 8 JDK, which is needed to build Java 9.
Choosing the default Java to use
If your system has more than one version of Java, configure which one your system uses by entering the following command in a terminal window
This will present you with a selection that looks similar to the following (the details may differ for you):
IBM Java
IBM provide JRE and SDK binaries for a number of architectures, including PowerPC. These are available via the IBM Downloads Page once you have registered.
There are two types of ‘InstallAnywhere’ package available to you: the ‘Archive/tgz’ only extracts the files to your system, whereas the ‘Installable’ package supposedly also configures your system. You can use either, both require additional configuration with Ubuntu. The ‘Installable’ package also provides an uninstall option.
To run the downloaded file use the following commands:
This launches an interactive program that guides you through the installation options. Extract the file to the directory of your choice (for example /usr/lib/jvm/java-6-ibm-powerpc).
If you also have openjdk installed then you’ll need to update the java alternatives:
You’ll need to repeat this for every command you need. For the mozilla plugin you can use:
Further guidance can be found in the IBM documentation (including a different way to link the plugin).
If you don’t use the mozilla plugin frequently then you can disable it for security. You can do this through the Firefox menus or there are Firefox extensions you can use to automate this.
Test the installation at the Sun Java test webpage and using the command:
Note, there are old PowerPC deb packages still in medibuntu (keep clicking refresh if you get 403 forbidden). These are probably the easiest way to install, although they are now lacking security updates, plus the latest browser plugin. For these reasons it is strongly advised that you download a newer Service Refresh Fix Pack directly from the IBM Downloads Page.
You may have to install libstdc++5 and libgtk1.2 packages to use old versions of IBM Java. If you installed a 1.4.2 version, and your processor is not a G5, you may have to perform another step to get it to work. For a G3 or G4, use the following command:
For a 604e or 603e, instead use:
You will have to log out or restart the computer for this to take effect.
GNU Compiler for Java
Install the java-gcj-compat-headless package using any installation method.
To install the development environment, install the java-gcj-compat-dev package using any installation method.
GCJ is a front end to the GCC compiler which can natively compile both Java(tm) source and bytecode files. The compiler can also generate class files. Gcjwebplugin is a little web browser plugin to execute Java applets.
It is targeted for Mozilla and compatible browsers that support the NPAPI. Others include the Eclipse Java Compiler, which is maintained by the Eclipse Foundation. Eclipse is an open-source Integrated development environment (IDE) written primarily in Java. The Eclipse open source community has over 60 open source projects.
Установка Java в Ubuntu 20.04
Программа, написанная для одной системы, будет без проблем работать в другой. Но для программ, написанных на Java, нужна специальная виртуальная Java-машина. В этой статье будет рассмотрена установка Java в Ubuntu 20.04 для разных версий программы. А также попытаемся разобраться во всём её многообразии.
Какую версию Java выбрать?
Сейчас разработкой Java занимается компания Oracle. До недавнего времени существовало две основных версии виртуальной машины Java:
Платформа распространялась в двух форматах:
Если вы разработчик, и хотите получить самую свежую версию Java, то стоит устанавливать Java 11. Это LTS-версия, которая будет поддерживаться до 2026 года. В ней было очень много улучшений и изменений, как в плане синтаксиса, так и для распространения. Теперь проприетарная версия доступна бесплатно только для некоммерческого использования. Для коммерческих целей необходимо заплатить или же устанавливать OpenJDK.
В Ubuntu и в других дистрибутивах Java поставляется в двух редакциях:
Выбор остается полностью за пользователем. Если нет необходимости что-то компилировать на Java, то будет достаточно установки JRE. Далее будет рассмотрена установка Java.
Установка Java 8 в Ubuntu 20.04
1. Как установить OpenJDK в Ubuntu 20.04
Если необходимо установить OpenJDK в Ubuntu, то никаких сторонних репозиториев подключать не нужно. Восьмая версия платформы есть в официальном репозитории Ubuntu 20.04. Чтобы установить JDK на Ubuntu необходимо выполнить команду:
Для установки JRE в Ubuntu необходимо выполнить команду
После этого можно узнать версию Java:
Версия 1.8.0 эквивалентна версии 8.
2. Как установить Oracle Java 8 в Ubuntu 20.04
Далее необходимо поставить галочку напротив пункта I reviewed and accept the Oracle Technology Network License Agreement for Oracle Java SE тем самым подтверждая принятия условия лицензионного соглашения.
Для скачивания файла необходимо войти в свою учетную запись Oracle или создать новую, только после этого начнется загрузка выбранной версии. После завершения загрузки необходимо создать директорию /usr/lib/jvm/:
sudo mkdir /usr/lib/jvm/
Распакуйте в неё скаченный ранее архив:
Добавьте исполняемый файл Java к списку утилиты для управления версиями 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
Или можно установить JRE-редакцию, предназначенную только для запуска программ:
После установки необходимо переключиться на 11 версию. Для этого выполните команду:
Введите необходимую цифру для выбора Java 11. В данном случае будет выбрана цифра 0:
После этого проверьте версию Java:
2. Как установить Oracle Java 11 в Ubuntu 20.04
Для установки проприетарной версии Java от корпорации Oracle необходимо скачать пакет JDK с официального сайта Oracle и добавить репозиторий для установки Java. Если просто попытаться выполнить команду для установки минуя скачивание JDK apt выдаст ошибку Oracle JDK 11 is NOT installed.
Далее необходимо поставить галочку напротив пункта I reviewed and accept the Oracle Technology Network License Agreement for Oracle Java SE тем самым подтверждая принятия условия лицензионного соглашения. Для скачивания файла необходимо войти в свою учетную запись Oracle или создать новую, только после этого начнется загрузка архива.
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 при помощи команды:
При появлении окна с лицензией нажмите на клавишу Tab далее нажмите на клавишу Enter:
В следующем окне снова нажмите на клавишу Tab и на клавишу Enter:
После этого проверьте версию Java:
Выбор версии Java
Если в системе установлено несколько версий Java, необходимо выбрать, какая из них будет использоваться по умолчанию. Для этого используется утилита update-java-alternatives. Для просмотра списка всех установленных версий необходимо выполнить команду:
Далее установите необходимую версию при помощи опции –set и задав полное имя Java:
Удаление Java из Ubuntu 20.04
Чтобы удалить ненужную версию Java, выполните одну из перечисленных ниже команд для удаления конкретной версии или выполните все команды поочередно для удаления всех версий Java:
Далее можно удалить PPA-репозиторий:
Выводы
В этой статье была показана установка Java на Ubuntu 20.04. Теперь после прочтения данной статьи вы знаете, как устанавливать Java и как выбирать необходимую версию по умолчанию. Надеюсь, информация из статьи была вам полезной.