How to run your first java program on ubuntu linux

Jul 26, 2012, by admin

java-on-linuxThis document supposes you have some kind of Java software development environment installed on your system such as Oracle Java, OpenJDK or IBM Java. If you don’t have a Java development environment setup please see the following document How to Install Oracle Java on Ubuntu Linux

If Java is installed on your system then our next task is setting up a clear environment in order to create our first Java program. Some people prefer to use an IDE( integrated development environment ) such as Eclipse IDE or NetBeans IDE to write their programs. Since it makes programming tasks less complicated when you are working with many Java class files.

java-on-ubuntuFor this example, we are going to work manually with Java programming without the use of an IDE. By this I mean using the Java JDK( Java development kit ), creating a directory, Java text file and making use of a text editor.

Steps run your first java program on ubuntu linux

1.Once Java is installed on your system, the next step will be to create a directory to hold your Java programs. Open up a terminal on Ubuntu Linux and create your Java applications directory.

2.Type/Copy/Paste: mkdir Java_Applications

  • This will create your Java_Applications directory

3. Next we are going to change into your Java_Applications directory

4.Type/Copy/Paste: cd Java_Applications

  •  This will change you into your newly created Java_Applications directory

5.Use a text editor such as nano or gedit to create a java file in this example we will use the traditional first program known as Hello world. This will open up a blank Java text file to work with and now we will insert some text into our Java file. So using nano or gedit we will issue the following command:

  •    Type/Copy/Paste: nano HelloWorld.java
  •         or
  •     Type/Copy/Paste: gedit HelloWorld.java

6.Enter the following code below:

    •  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 on 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);

}

}

1.Save the file as HelloWorld.java

2.Next we are going to compile the HelloWorld.java file into a Java class file by issuing the following command below.

  •  Type/Copy/Paste: javac HelloWorld.java

3.Run or execute your Java class file by issuing the following command.

  •   Type/Copy/Paste: java HelloWorld