This document assumes that you have some Java development program installed on your system, such as Oracle Java, OpenJDK, or IBM Java. If you don't have a Java development program installed, see the following How to Install Oracle Java on Ubuntu Linux document.
If Java is installed on your system, then your next task is to set up a new environment to create your first Java program. Some people prefer to use an integrated development environment such as Eclipse IDE or NetBeans IDE to write their programs, as it makes the task of programming less complicated when working with many Java class files.
For this example, we're going to manually work with Java programming without using an IDE. By this I mean that we will use the Java JDK (Java Development Kit), create a folder, a Java text file and use a text editor as a program.
Steps
Step 1. Once Java is installed on your system, the next step is to create a directory to hold your Java programs
Open a terminal on Ubuntu Linux and create your Java applications folder.
Step 2. Type / Copy / Paste:
mkdir Java_Applications
-
This will create your Java_Applications folder
Step 3. Then we'll go to your Java_Applications directory
Step 4. Type / Copy / Paste:
cd Java_Applications-
This will place you in your newly created Java_Applications directory
Step 5. Use a text editor such as nano or gedit to create a java file
In this example we will use the first traditional program called Hello World. We will open the empty Java file to work with and insert some text inside the Java file. Then using nano or gedit we will enter the following command:
-
Type / Copy / Paste:
dwarf HelloWorld.java
-
Type / Copy / Paste::
gedit HelloWorld.java
or
Step 6. Enter the following code:
-
Type / Copy / Paste:
import javax.swing. *; public class HelloWorld extends JFrame {public static void main (String args) {new HelloWorld (); } public HelloWorld () {JPanel panel1 = new JPanel (); JLabel label1 = new JLabel ("Hello, World, this is my first Java program in Ubuntu Linux"); panel1.add (label1); this.add (panel1); this.setTitle ("Hello World"); this.setSize (500, 500); this.setDefaultCloseOperation (JFrame. EXIT_ON_CLOSE); this.setVisible (true); }}
Step 7. Save the file as HelloWorld.java
Step 8. Then we are going to compile the HelloWorld.java file into a Java class file by running the following command:
-
Type / Copy / Paste:
javac HelloWorld.java
Step 9. Run or run your Java class file by entering the following command:
-
Type / Copy / Paste:
java HelloWorld