Hello World

Our first program will print the classic “hello world” message. Here’s the full source code.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("hello world");
    }
}

To run the program, compile the code into a .class file and then use java to execute it.

$ javac HelloWorld.java
$ java HelloWorld
hello world

Sometimes we’ll want to build our programs into binaries that can be executed directly. In Java, this usually means creating a JAR (Java ARchive) file.

First, compile the code and then package it into a JAR file:

$ javac HelloWorld.java
$ jar cfe HelloWorld.jar HelloWorld HelloWorld.class
$ ls
HelloWorld.class   HelloWorld.java    HelloWorld.jar

We can then execute the JAR file directly using the java -jar command.

$ java -jar HelloWorld.jar
hello world

Now that we can run and build basic Java programs, let’s learn more about the language.