- How To Compile and Run Java Program in Linux
- How to Compile Java Program
- How to Run Java Program
- Установка Java в Linux
- Чем отличается JDK от JRE
- Установка Java в Linux своими руками
- Установка Java в Ubuntu
- JRE и JDK
- Установка Java в ArchLinux
- Установка Java в CentOS
- Выбор версии Java
- Ubuntu
- ArchLinux
- CentOS
- Настройка переменных окружения
- Выводы
- Hello World in Java on Linux
How To Compile and Run Java Program in Linux
Today I’ll explain how to compile and run Java code on Linux environment.
Personally, I like Ubuntu, that’s why I’ll show you how to do it there.
First of all, you have to be sure that Java is installed on your machine.
Correct output is:
If it’s not installed you can do it easy:
Now change directory to your project source folder.
Inside of my project I have a class Car, that I wrote when I talked about the transient keyword in Java.
It looks like this:
How to Compile Java Program
To compile this class I call Linux Java compiler:
If everything was OK you should find a new file Car.class near Car.java.
Our class is compiled, the next step is to run compiled Java class on Ubuntu.
How to Run Java Program
In the previous section, I compiled Java code in Linux.
Now I’m going to show how to run Java program.
Just point Java to compiled class like this:
Note that you should run Java class from the source folder.
For example, if I change directory to project (one level upper than src folder).
and try to run the same class:
So you have to be sure that you’re running your Java code on Ubuntu from the source folder.
For compiling process it doesn’t matter.
As you can see it’s easy to compile and run Java on Linux.
Personally, I prefer Java programming on Linux instead of Windows.
I think Java developers should know at least basic Linux commands.
Источник
Установка Java в Linux
В этой статье речь пойдёт о проприетарной версии Java. Часто происходят ситуации, когда пользователь пытается открыть какую-либо программу на Java, а она либо вообще не запускается, либо пытается это сделать с помощью OpenJDK (Java Development Kit). Но вместо результата вы получаете кучу ошибок (как например с Minecraft). В данных ситуациях вам, скорее всего, поможет установка Java от Oracle.
Я вам расскажу, как установить JRE (Java Runtime Environment) и JDK (Java Development Kit) 8 версии на такие дистрибутивы, как Ubuntu, CentOS и Arch, а также как выбрать нужную среду по умолчанию.
Чем отличается JDK от JRE
- JRE — Java Runtime Environment — это среда выполнения Java. Предназначена для обычного использования. Позволяет запускать приложения, написанные на языке Java.
- JDK— Java Development Kit — стандартная версия платформы Java, предназначенная для разработки. Это специальный пакет разработчика, в который входят документация, различные утилиты, компилятор, библиотеки классов, а также сама JRE.
Установка Java в Linux своими руками
Скачать архив с необходимой вам версией вы можете с официального сайта. Далее вам надо перенести его в желаемую директорию и распаковать. Рекомендую /opt/java, далее она и будет использоваться. Сделайте это, используя следующие команды:
sudo tar -xzf /opt/java/jre*.tar.gz
Где «*» — версия Java.
Загрузите архив со средствами разработчки с официального сайта компании Oracle. Также перенесите его в желаемую директорию и распакуйте:
sudo tar -xzf /opt/java/jdk*.tar.gz
Установка Java в Ubuntu
JRE и JDK
Для установки проприетарной Oracle Java вам необходимо добавить репозиторий, обновить индексы пакетов и установить Java. В Ubuntu, начиная с 18 релиза, это делается автоматически после добавления репозитория.
Внимание! Будут установлены как JRE, так и JDK. Сначала добавим репозиторий и обновим списки пакетов:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
В процессе установки необходимо будет принять лицензионное соглашение:
sudo apt-get install oracle-java8-installer
Установка Java в ArchLinux
В официальных репозиториях есть только OpenJDK. Поэтому придётся воспользоваться пакетом из AUR(вы можете, конечно, руками установить Java от Oracle, но AUR проще). Установка производится всего одной командой:
JDK так же можно установить, используя AUR. Просто выполните команду:
Установка Java в CentOS
Для RHEL, Fedora, Cent OS, OpenSUSE есть официальный RPM-пакет, который вы можете скачать с официального сайта. Чтобы установить пакет из терминала, воспользуйтесь этой командой:
sudo rpm -i /путь/к/файлу/jre-*.rpm
где «*» — версия Java. Или же примените любую графическую утилиту.
Средства для разработчика вы можете скачать на сайте Oracle, ссылка на который есть в верху статьи. Для установки из терминала, используйте команду:
Где «*» — версия Java. «
» — указывает, что путь начинается.
Выбор версии Java
Ubuntu
Для переключения на 8 версию Java используйте следующую команду:
sudo update-java-alternatives -s java-8-oracle
Чтобы автоматически установить переменные среды, воспользуйтесь командой:
sudo apt-get install oracle-java8-set-default
Или же вы можете установить альтернативы сами. Делается это с помощью следующих команд:
sudo update-alternatives —install /usr/bin/java java / usr / lib / jvm / java-8-oracle/bin/java 1
sudo update-alternatives —install / usr / bin / javaс javaс / usr / lib / jvm / java-8-oracle / bin / javaс 1
sudo update-alternatives —install / usr / bin / javaws javaws / usr / lib / jvm /java-8-oracle / bin / javaws 1
Теперь осталось выбрать версии исполняемых файлов java, javaws и javac, которые будут использоваться по умолчанию:
sudo update-alternatives —config java
sudo update-alternatives —config javac
sudo update-alternatives —config javaws
ArchLinux
Для начала просмотрите список установленных сред:
Затем установите необходимую вам:
archlinux-java set имя_среды
archlinux-java set java-8-jre/jre
CentOS
Выбрать необходимую среду можно с помощью команд, данных ниже (так же, как и в Ubuntu). Вам нужно будет просто выбрать цифру, соответствующую номеру версии:
sudo update-alternatives —config java
sudo update-alternatives —config javac
sudo update-alternatives —config javaws
Настройка переменных окружения
Чтобы настройки были доступны для всех пользователей, будем использовать файл /etc/profile. Откройте его для редактирования любым текстовым редактором с помощью команды sudo и добавьте в конец следующие строки:
- export JAVA_HOME=/opt/java/jdk*/
- export JRE_HOME=/opt/java/jdk*/jre
- export PATH=$PATH:/opt/java/jdk*/bin:/opt/java/jdk*/jre/bin
- Вместо пути по умолчанию /opt/java укажите тот, который использовали;
- Если вы используете не JDK, а JRE, то в пути у вас так же будет не «jdk*», а «jre*»;
- «*» — версия Java, которая у вас установлена.
Выводы
В данной статье мы подробно разобрали процесс установки и настройки Java в различных дистрибутивах Linux. Если остались вопросы, спрашивайте в комментариях!
Источник
Hello World in Java on Linux
This DrJava-based Java programming environment is no longer being supported (because DrJava in no longer being actively developed and DrJava is incompatible with Java 11). It has been replaced by the following IntelliJ-based programming environment for Linux.
This document instructs you on how to setup a Java programming environment under Linux. It also provides a step-by-step guide for creating, compiling, and executing your first Java program using either DrJava or the command line. We assume some familiarity with the command line. All of the software is freely available on the web.
0. Install Java |
You will use the Java Platform, Standard Edition Development Kit (JDK 8).
Log in to the user account in which you will be programming. Your account must have Administrator privileges and you must be connected to the Internet.
Launch your shell. We’ll assume that the command prompt looks like the following (though yours will likely differ):
/ is shorthand for your home directory.
Install the Java Platform, Standard Edition Development Kit (JDK 8), either from Oracle or OpenJDK. Most Linux distributions provide their own mechanism for installing software. For example, here are the commands on Ubuntu for Oracle JDK 8:
To confirm that the Java compiler is installed, type the command in boldface below and check that the results match:
To confirm that the Java interpreter is installed, type the command in boldface below and check that the results match:
1. Install a Programming Environment |
These steps install and configures our textbook libraries, DrJava, Checkstyle, and Findbugs. If you do not want DrJava, Checkstyle, or Findbugs, simply skip the corresponding step.
Create a directory /usr/local/introcs.
Download the textbook libraries from stdlib.jar and the Java wrapper scripts from javac-introcs and java-introcs.
Download DrJava from drjava.jar, the wrapper script from drjava, and the configuration file from .drjava.
Download Checkstyle 8.2 from checkstyle.zip; our Checkstyle configuration file from checkstyle-introcs.xml; and the Checkstyle wrapper script from from checkstyle-introcs
Download Findbugs 3.0.1 from findbugs.zip; our Findbugs configuration file from findbugs.xml; and the Findbugs wrapper script from findbugs-introcs.
2. Create a Program in DrJava |
Now you are ready to write your first Java program. You will develop your Java programs in an application called DrJava. DrJava features many specialized programming tools including syntax highlighting, bracket matching, auto indenting, and line numbering.
If you use a file manager such as Konqueror or Nautilus, you can launch DrJava by double-clicking the drjava.jar file. Otherwise, launch DrJava from the command line by typing:
If you copied the .drjava file to your home directory, these customizations should already be included:
Display line numbers by selecting Edit -> Preferences -> Display Options -> Show All Line Numbers.
Set the indentation level to 4 by selecting Edit -> Preferences -> Miscellaneous -> Indent Level -> 4.
Set the Java classpath by selecting Edit -> Preferences -> Resources -> Extra Classpath -> Add and add the following entry:
In the main DrJava window, type the Java program HelloWorld.java exactly as it appears below. If you omit even a semicolon, the program won’t work.
3. Compile a Program from DrJava |
It is now time to convert your Java program into a form more amenable for execution on a computer. To do this, click the Compile button. If all goes well, you should see the following message in the Compiler Output pane at the bottom:
If DrJava complains in some way, you mistyped something. Check your program carefully, using the error messages in the Compiler Output pane as a guide.
4. Execute a Program from DrJava |
Now it is time to run your program. This is the fun part.
Type the following in the Interactions pane at the bottom. By convention, we highlight the text you type in bold.
5. Compile a Program from the Shell |
You will use the javac command to convert your Java program into a form more amenable for execution on a computer.
From the shell, navigate to the directory containing HelloWorld.java, say
/hello, by typing the cd (change directory) commands below:
6. Execute a Program from the Shell |
You will use the java command to execute your program.
- From the shell, type the java command below.
To make our textbook libraries accessible to Java, use the command java-introcs instead. For example, type the following two commands to test standard drawing and standard audio:
7. Checkstyle and Findbugs |
You can use Checkstyle and Findbugs to check the style of your programs and identify common bugs.
To run Checkstyle, type the following command in the Terminal:
To run Findbugs, type the following command in the Terminal:
Troubleshooting |
My distribution of Linux is < Gentoo, Debian, Ubuntu, Fedora, Red Hat, SuSE, Mandriva, or Slackware >. How should I modify the instructions? We haven’t tested out these instructions on all flavors of Linux, but the instructions should be identical except for installing Java. We recommend using your distribution’s package manager (such as portage, apt, emerge, or yum) to install Java. Here are some instructions for installing OpenJDK.
Can I use a different version of Java? Any version of Java 8 (either Oracle or OpenJDK) or later should work fine.
I had to manually enter the location of tools.jar in DrJava, but it doesn’t seem to have any effect. Any suggestions? This setting doesn’t take effect until you restart DrJava.
Can I use a different IDE? Yes, feel free to use another IDE (such as Eclipse) but you will have to configure the IDE properties yourself (such as the classpath).
How do I determine which shell I’m running? Type the following command:
How can I check that /usr/local/bin is in my PATH? From the shell, type the following command:
How can I add /usr/local/bin to my PATH? It depends significantly on your Linux distribution, shell, and user configuration. In the bash shell, this generally means adding the following line to either your .bash_profile, .profile, or .bashrc file. For other common shells, this could mean updating your .cshrc, .tcshrc, or .zcshrc files.
When I compile or execute a program from the shell that uses one of the textbook libraries, I get an error. How can I fix this? First, make sure that you are using the javac-introcs and java-introcs wrapper scripts. Next, verify that you have the file /usr/local/introcs/stdlib.jar. Reset Interactions; from the shell, type Ctrl-c.
When using standard input, how do I signify that there is no more data? If you are entering input from the keyboard, type Ctrl-d for EOF (end of file) from either DrJava or the shell. —>
Last modified on August 14, 2019.
Copyright © 2000–2019 Robert Sedgewick and Kevin Wayne. All rights reserved.
Источник