In this article, I will show you how to run java programs in Ubuntu in the simplest and easiest way.
Join the channel Telegram of the AnonyViet 👉 Link 👈 |
How to Run Java Programs in Ubuntu
Step 1: Install Java Compiler
To run a Java program, you first need to compile the program. The Java compiler is part of the JDK (Java Development Kit). You need to install the JDK to compile and run Java programs.
First, check if you have Java compiler installed on your system with the following command:
javac --version
If you get an error like “Command ‘javac’ not found, but can be installed with” it means you need to install the ava Development Kit.
The simplest way to install the JDK on Ubuntu is to use the default package manager from Ubuntu:
sudo apt install default-jdk
You will be asked to enter your account password. When you enter your password, nothing will show up on Terminal. That is completely normal. Just enter your password. When asked, press the enter key or the Y key.
The above command should work for other Debian and Ubuntu based distributions like Linux Mint, elementary OS, etc. For other distributions, use your distribution’s package manager. The package name may also be different.
Once installed, verify the version of javac.
Step 2: Compile Java Programs in Linux
You need a Java program file. Suppose you create a new Java program file named HelloWorld.java and it has the following content:
class HelloWorld{ public static void main(String args[]){ System.out.println("Hello World"); } }
You can use the Nano editor in Terminal or the Gedit graphical text editor to code your Java programs.
javac HelloWorld.java
If there are no errors, the above command will produce no output.
When you compile a Java program, it generates a .class file with the class name that you used in your program. You must run this .class file.
Step 3: Run the file .class
You do not need to specify the .class file extension here. Just enter the name of the class. And this time, you use the java command, not javac.
java HelloWorld
The program will print Hello World on the Terminal screen.
And that’s how you can run a Java program in Terminal Linux.
This is the simplest example. The sample program has only one class. The Java compiler creates a .class file for each class in your program. Things will get complicated for larger programs and projects.
That’s why I recommend installing Eclipse on Ubuntu for Java programming. Alternatively, you can also create a Minecraft Server on Linux here.