- How To Compile and Run Java Program in Linux
- How to Compile Java Program
- How to Run Java Program
- Как скомпилировать файл .java на Ubuntu?
- 4 ответа
- How to compile a .java file on Ubuntu?
- 5 Answers 5
- How to compile and run java files on Linux
- Creating a java program file
- Compiling a java program file using the command line
- Ubuntu Documentation
- Installing the GNU C compiler and GNU C++ compiler
- Installing the GNU Java compiler
- Installing the GNU Fortran compilers
- Installing the GNU autotools
- 32-bit Builds on AMD64
- Installing the Intel Compiler Suite Professional Edition 10.x
- Get the License Number and Extract to a path without spaces
- On 64-bit systems you may also need to issue these commands
- Run the Installation Script
- Edit /etc/bash.bashrc to add the installation path to the PATH environment variable
- Installing the X11 development compilers
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 на Ubuntu?
Как я могу скомпилировать файл .java?
Какие программы мне понадобятся? Если мне нужен Java JDK, мне также понадобится помощь в установке этого. Я очень новичок в Ubuntu, поэтому любая программа, которую мне нужно установить, мне понадобится учебник по установке.
4 ответа
OpenJDK работает лучше всего для меня. Это просто, и я никогда с ним не сталкивался. Просто выполните следующие простые шаги:
From Terminal install open jdk Напишите программу java и сохраните файл как filename.java Теперь для компиляции используйте эту команду с терминала . Если все работает хорошо, тогда необходимо создать новый файл «filename.class». Для запуска вашей программы, которую вы только что скомпилировали, введите следующую команду в терминале:
Вы можете использовать любой текстовый редактор (например, gedit),
замените имя файла на любое имя, которое вы хотите
, вам нужно быть в том же каталоге, что и «настоящий рабочий каталог» (полученный при запуске pwd) во время выполнения команды с терминала. [!d14 ]
Если, например, ваш файл my_file.java:
Вы хотите сделать:
Тем не менее, это общепринятое соглашение, дающее классы и файлы с тем же именем.
Вам необходимо установить JDK, Java Development Kit. Ubuntu содержит metapackage default-jdk, который зависит от выбранного в настоящее время JDK. Теперь это openjdk-6-jdk.
Чтобы скомпилировать файл Java в исполняемый файл .class, вы можете запустить
и запустить его
Это самый простой случай использования, и в основном он не работает, потому что классы java в основном зависят от других классов Java, размещенных в библиотеках.
Таким образом, вы, вероятно, хотели бы использовать более сложные решения. Большинство текстовых редакторов поддерживают подсветку синтаксиса Java, например default-jdk , kate или vim, но они не решают проблему с компиляцией.
У вас есть другой вариант — вы можете установить полнофункциональная Java IDE. Ubuntu поставляется с главными Java IDE OpenSource — kate и Eclipse.
Просто введите sudo apt-get update, а затем sudo apt-get install openjdk-7-jdk для быстрой установки для java7, затем вы можете играть в игры с помощью java: -)
Для получения более подробной официальной документации по Java, перейдите по этой ссылке.
Источник
How to compile a .java file on Ubuntu?
How can I compile a .java file?
What programs will I need? If I need the Java JDK I will also need help installing that. I’m very new to Ubuntu, so any program that I need to install I will need a tutorial on how to install them.
5 Answers 5
To compile the file, open your terminal and type
To run the generated class file, use
But to do this you need to have the Java JDK installed in your computer. You can install it with the instructions in How do I install Java?.
OpenJDK works best for me. It’s simple and I have never faced any problem with it. Just follow these simple steps:
From Terminal install open jdk
Write a java program and save the file as filename.java
Now to compile use this command from the terminal
If everything works well then a new «filename.class» file should be created.
To run your program that you’ve just compiled type the command below in terminal:
You can use any text editor (like gedit) ,
replace the filename with watever name you want
you need to be on same directory as the «present working directory» (got by running pwd ) while running the command from terminal.
If for example your file is my_file.java :
However, it is a common convention to give classes and files the same name.
You need to install a JDK, Java Development Kit. Ubuntu contains a metapackage default-jdk, which depends on currently prefered JDK. Now it is openjdk-6-jdk.
To compile a Java file to runnable .class file you can run
It is the most simple use-case and mostly it doesn’t work because java classes mostly depends on other java classes placed in libraries.
So you would probably like to use some more sophisticated solutions. Most text editors supports Java syntax highlighting, for example jEdit, kate or vim, but they don’t solve your compilation issue.
You have another option — you can install a full featured Java IDE. Ubuntu comes with both main OpenSource Java IDEs — NetBeans and Eclipse.
Источник
How to compile and run java files on Linux
Many new computer science students and new to programming young devs when exposed to a programming language. They use CLI tools to compile and run the program. So here is the basic guide on how to compile and run java files on Linux using the command line.
Java is one of the most popular programming languages out there, millions of the developers use it to develop various types of applications and services. It is most famously known for Android application development and industrial use. So now let’s take a demo on how to compile and run java files on Linux.
Creating a java program file
Before the compilation, We first need to write a program in java. Use any text editor you want and create a java program file.
You can also just copy and paste the code below into the editor and save the file as HelloWorld.java. We will use this file to demonstrate the process.
Compiling a java program file using the command line
Now open the terminal and type the below command in order to compile java program code into bytecode.
The above command will generate a HelloWorld.class file which is containing the bytecode. So to run the program just execute this class file into the JVM using the below command.
If everything is as per the plan then you will see the output as :
This is how you can compile and run a java file using the command line. Let me know what you think about it in the comment section below.
Источник
Ubuntu Documentation
Installing the GNU C compiler and GNU C++ compiler
To install the gcc and g++ compilers, you will need the build-essential package. This will also install GNU make.
build-essential contains a list of packages which are essential for building Ubuntu packages including gcc compiler, make and other required tools.
Now, you should able to compile software using C / C++ compilers.
To install the manpages for c and c++ development, install the manpages-dev package.
Installing the GNU Java compiler
Note that GNU’s Java compiler is not the same as the one developed and distributed by Sun Microsystems, and will not provide Java to the firefox browser. For that, please see Java. To install gcj, the GNU Java compiler, install the following package: gcj.
gcj can be used to:
- compile .java files to bytecode (.class files).
- compile .java files to a linux-executable.
To install the GNU Java bytecode interpreter, you need the gij package.
To have gcj compile to executables, install libgcj6-dev (otherwise an error during compilation occurs: libgcj.spec: No such file or directory). Use synaptic to install libgcj6-dev.
Installing the GNU Fortran compilers
To install the GNU Fortran 77 compiler — g77, you need the g77 package.
To install the GNU Fortran 95 compiler — gfortran, the package is: gfortran.
Installing the GNU autotools
To install autoconf and automake, you need the autoconf and automake packages.
Apt-get will tell you to explicitly choose a version of automake. If, for example, you decide to use automake1.9, you need to specify the version, such as the automake1.9 package.
32-bit Builds on AMD64
The GNU compilers have options that allow them to create 32-bit object and executable files on 64-bit operating systems, and vica versa. The critical options are -m32 (to build 32-bit) and -m64 (to build 64-bit).
These options will be present when you install the compiler of your choice. However, they won’t actually work unless you install several additional packages.
The first thing you will need is the multilib package for the compiler you are using. For example, to add multilib support to the default version of g++ (4.1 in gutsy), you would install
The multilib packages are compiler runtime packages. Now, you need 32-bit (or 64-bit) versions of whatever libraries you need to link your application program. 64-bit packages have names that start with lib64. Install these on 32-bit systems to support 64-bit builds. 32-bit packages have names that start with lib32. Install these on 64-bit systems to support 32-bit builds. Whatever else you are doing, you will probably need
Installing the Intel Compiler Suite Professional Edition 10.x
Using the Intel compilers for C, C++, and FORTRAN requires installing 32-bit libraries for Ubuntu if you are using a 64-bit system. Please ensure you have these packages:
gcc, build-essential, libc6-dev (see above)
ia32-libs, g++-multilib, and libc6-dev-i386 (for 64-bit systems)
32-bit packages starting with lib32 (for 64-bit systems)
alien and rpm for installing the RPM packages that Intel distributes.
libstdc++5 and libstdc++5-3.3-dev for good measure because Intel’s builds depend on these runtimes.
before you attempt installing the Intel Compiler Suite.
Get the License Number and Extract to a path without spaces
Ensure that you have obtained the license number for your installation and extracted the downloaded installation archive into a path that does not contain any spaces. This last statement is utterly important. The installer script that comes with the package has a bug that does not allow you to install the compiler suite if you have any spaces in the installer script path.
On 64-bit systems you may also need to issue these commands
because the chklic_32_64 license checking utility from Intel dynamically links to these libraries.
Once you’re done preparing to install the compiler suite, it’s time to go to the installer directory and install the compiler (be sure to also read through accompanying documentation; e.g., README, INSTALL.txt):
Run the Installation Script
After installing the compiler, you need to tell your shell the location of these executables by adding their parent paths to the PATH environment variable.
Edit /etc/bash.bashrc to add the installation path to the PATH environment variable
Where 10.1.012 is the version of the compiler suite installed.
Installing the X11 development compilers
Install script for X11 development libs
InstallingCompilers (последним исправлял пользователь andrius-zilenas 2012-08-10 10:18:50)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Источник