Install OpenJDK and Set JAVA_HOME Path in Ubuntu
Mainly Java-based programs need to run the Java Runtime Environment (JRE) smoothly regardless of the operating system. Now we can discuss how to set JAVA_HOME in Ubuntu.
1. Install OpenJDK on Ubuntu
Note: make sure that you have updated an advanced package tool (APT) before you start the install OpenJDK.
If you want to update APT, you can use the following syntax.
Press Ctrl + Alt + T to open the terminal and enter the following command to install OpenJDK.
Wait for the system to finish the installation then move to the second step.
2. Set JAVA_HOME Path
Now your installation is completed. All you have to do now set the “JAVA_HOME” and “PATH” environment variables.
Firstly make sure that your environment variable installations point to a valid installation.
normally, the ubuntu path is usr/lib/jvm/java-8-openjdk-amd64/
then you can execute the following commands.
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
When your JAVA_HOME path has been successfully saved, execute the following commands to check.
3. Add JAVA bin directory to the PATH variable
Like added JAVA_HOME path, now we will update the PATH variable.
Like check the JAVA_HOME path, You can check the PATH variable by entering the following command.
4. Test JAVA
You have successfully installed OpenJDK on your computer. So executed the following command you can verify your installation.
Through this simple tutorial, you have now configured the JAVA_HOME variable in your operating system.
How to Install Java on Ubuntu 18.04
This article will teach you how to install Java on Ubuntu 18.04. The commands will work on any private server or computer running the latest version, Ubuntu 18.04 Bionic Beaver, as well as 16.04, and any other Long Time Support (LTS) releases. Java is usually distributed in three editions, namely Micro (ME), Enterprise (EE), and Standard Edition (EE). For this guide, we’ll use Java SE 11 (LTS).
Overall, Java is one of the leading programming languages in the world. It’s created to have as little dependencies as possible, which allows application developers to apply the “write once, run anywhere” philosophy. As a result, a compiled Java code can operate on any platform which supports Java. You can utilize it to build anything from simple web applications to more advanced pieces of software.
Without further ado, let’s see how we can install Java on Ubuntu 18.04.
JDK or JRE?
The OpenJDK (Java Development Kit) and Oracle JRE (Java Runtime Environment) are the two main kits you’ll work with. Oracle Java contains the JVM, the Java program, alongside other infrastructures, while the JDK is a superset of JRE. The JDK is essentially an SDK (software development kit), as it gives you access to everything in JRE plus tools such as jdb, javadoc, and the compiler itself – javac.
If you’re not interested in compiling Java software, the JRE will do just fine. If this changes, you can update it later.
The following commands imply you are already using a root user, but in case you’re not, you should add sudo at the beginning of your commands.
Install Java on Ubuntu Using the Default Package Manager
The first method to install Java on Ubuntu is through the default packages. Begin the process by updating the current packages to the latest version:
Once it finishes, install the latest version of Java Runtime Environment (JRE) by executing this following command:
It is also possible to install the Java Development Kit (JDK) instead. It is required by specific software or used to compile Java programs. JDK includes JRE, therefore there’s no disadvantage if you choose this method instead.
That’s it, Java is ready for use on your Ubuntu system. You can double-check if it was properly set up with these commands:
The output will be similar to:
Install Java on Ubuntu via Oracle JDK
Alternatively, it is possible to install Java on Ubuntu using the official Oracle JDK. Begin by updating your current packages to the latest version:
For this example, we’ll use a third party library managed by WebUpd8. In order to implement it easier, install the following package first:
Next, get the Java Uprising PPA with the following command:
You might even want to run a quick update while you’re at it:
Finally, you can install Java on your Ubuntu system by executing the following command and following the on-screen instructions:
Then make sure to choose “Yes” using your keyboard to accept the license terms and your installation will begin.
That’s it! Java is successfully installed. You may verify it by checking the version with these two commands:
A similar output will appear:
Managing Java
A single server can have multiple Java installations. You can set the default version using the following command line:
The following output will appear:
Enter the number from the selection menu which you wish to use as the default one. You can also do this with other Java commands, such as:
Setting the Java Home Environment
Another useful thing to know is how to set the JAVA_HOME variable. Most applications require it to find the location of your Java installation. The previously used command can help you locate the Java installation path:
Once you’ve copied the installation path, you will need to edit the environment file located in the etc directory:
Add the following line at the end to set the JAVA_HOME value:
Important! Don’t forget to update it with the actual path to your Java installation.
Press CTRL+X to finish editing and save the changes. Next, make the changes by applying this command:
You can double-check if it’s active by entering:
Conclusion
Congratulations, you now know how to install Java on Ubuntu 18.04. You’ve also learned some basics, such as setting the default Java version and defining the JAVA_HOME variable.
If you found this article useful, feel free to share it with the world. If you have any tips, suggestions, or ideas of your own, we eagerly await them in the comment section below.
Learn What Else Ubuntu Can Do!
Edward is a content editor with years of experience in IT writing, marketing, and Linux system administration. His goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.
How to set JAVA_HOME for Java?
I’ve installed a version of Java. How can we set the $JAVA_HOME environment variable correctly?
3 Answers 3
You can set your JAVA_HOME in /etc/profile as Petronilla Escarabajo suggests. But the preferred location for JAVA_HOME or any system variable is /etc/environment .
Open /etc/environment in any text editor like nano or gedit and add the following line:
(java path could be different)
Use source to load the variables, by running this command:
Then check the variable, by running this command:
Update
Usually most linux systems source /etc/environment by default. If your system doesn’t do that add the following line to
Установка переменных JAVA_HOME / PATH в Unix/Linux
Не знаете как установить переменные JAVA_HOME и PATH для каждого пользователя в соответствии с вашей системой Linux? Тогда эта статья «Установка переменных JAVA_HOME / PATH в Linux» именно для Вас. Я напишу ее в качестве заметки, чтобы потом быстренько вспомнить и прописать Java_Home и Path на ОС для каждого пользователя ( если понадобится).
Установка переменных JAVA_HOME / PATH в Unix/Linux
/ .bash_profile является сценарий запуска, который обычно выполняется один раз. Это конкретный файл используется для команд, которые выполняются, когда нормальные входе пользователя в систему. Common использует для .bash_profile должны установить переменные окружения, такие как PATH, JAVA_HOME, чтобы создать псевдонимы для команд оболочки, и установить права доступа по умолчанию для вновь создаваемых файлов.
Установка JAVA_HOME / PATH для одного пользователя
Зайдите в свой аккаунт (учетную запись) и откройте файл .bash_profile в любом редакторе:
Установите JAVA_HOME как показано используя синтаксис export JAVA_HOME=<path-to-java>. Если ваш путь такой как у меня /usr/lib/jvm/java-1.6.0-openjdk-i386/bin/java, то тогда пропишите:
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-i386/bin/java
Чтобы установить PATH пропишите:
Замените путь /usr/java/jdk1.5.0_07 на свой. Сохраните и закройте файл. Просто выйдите и зайдите обратно (перелогиньетсь), чтобы увидеть изменения или чтобы все изменения вступили в силу, выполните команду:
Чтобы проверить отображение новых настроек, используйте команды:
Совет: Используйте следующую команду, чтобы узнать точный путь Java под UNIX / Linux:
Пожалуйста, обратите внимание, что файл
/.bashrc похож на
/.bash_profile но работает только для оболочки Bash и .bashrc работает для каждой новой Bash оболочки.
Установка JAVA_HOME / PATH для всех пользователей
Вам нужно добавить строки в глобальный файл конфигурации в /etc/profile ИЛИ /etc/bash.bashrc чтобы внести изменения для всех пользователей:
Добавьте переменные PATH / JAVA_PATH следующим образом:
Сохраните и закройте файл. Еще раз вам нужно ввести следующую команду, чтобы немедленно активировать настройки:
Но если не будет работать, есть еще 1 способ прописать все это дело! Сейчас я покажу как это можно сделать.
1. Устанавливаем переменные среды:
2. Выполните команду чтобы перезапустить все только что прописанные настройки:
3. Тест, если среда Java успешно установлена, введите команду в терминале чтобы проверить работу:
Установка переменных JAVA_HOME / PATH в Unix/Linux завершена.
One thought on “ Установка переменных JAVA_HOME / PATH в Unix/Linux ”
Спасибо за гайд, работает как часы. Первых пунктов до bash_profile включительно хватило. Версия х64. Пути и названия свои. Проверил еще javac -version. Вопрос к автору. Где эту информацию искать на сайте оракла?
Добавить комментарий Отменить ответ
Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.