Getting started with Java on Ubuntu

How to Write and Run a Simple Java Program

Java is a high-level, general-purpose programming language originally developed by Sun Microsystems. It is known for its portability, meaning that Java code can run on different platforms, such as Windows, Mac OS, and Linux, without needing to be recompiled for each platform. Java is widely used for developing: web applications, enterprise applications, games and It is also the language of choice for developing Android applications!

In this post, we will write a simple program in Java on Ubuntu.

Getting started

Install the openjdk package, OpenJDK is an open-source implementation of the Java Platform, this will enable us to compile and run Java code:

sudo apt install openjdk-19-jdk-headless -y

Open a file named Main.java:

vim Main.java

Copy and paste the "Hello-world" sample code:

public class Main {
  static void helloWorld() {
    hello("World");
  }
  static void hello(String name) {
    System.out.println("Hello " + name + "!");
  }
  public static void main(String[] args) {
    if (args.length != 0) {
      hello(args[0]);
    } else {
      helloWorld();
    }
  }
}

Compile the Main.java file into a Java class file by issuing the following command below:

javac Main.java

Run the program:

java Main

If you followed correctly all the steps you should now see "Hello World!" printed in the terminal! The code is not the average Hello-World program and can also greet you! Add your name as a parameter of the executable like:

java Main Marco

Yep, it says: "Hello Marco!"

Conclusions

This was a simple guide to get you started with Java on Ubuntu, to get an overview of the language syntax I recommend having a look at the Java Tutorial from w3schools.

Did you find this article valuable?

Support Marco's blog by becoming a sponsor. Any amount is appreciated!