Your First Java Program: Hello World

Let us write the Hello World program, which prints a message on the screen. We will do it two times: first the classic way, which every Java book and every older project uses, and then the new short way of Java 25.

The classic Hello World

Save this in a file named Main.java. The name of the file must be the same as the name of the public class, with the same capital letters.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Output

Hello, World!

Understand each part

CodeMeaning
public class MainA class named Main. In Java all code lives inside classes
public static void main(String[] args)The starting point. The JVM calls this method first
publicAnyone can call it (the JVM needs it)
staticIt belongs to the class, so the JVM can call it without making an object
voidIt does not return a value
String[] argsThe command line arguments, as an array of text
System.out.println(…)Prints the text and moves to a new line

Compile and run in two steps

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Terminal

$ javac Main.java
$ java Main
Hello, World!

You can also run a single file in one step. Java compiles it in the memory and runs it at once:

Terminal

$ java Main.java
Hello, World!

The short way in Java 25

Java 25 has compact source files and instance main methods. For small programs you do not need the class and the public static words. The class IO has easy print methods too:

void main() {
    IO.println("Hello, World!");
}
Output

Hello, World!

This is great for learning and for small scripts. For real projects, and for the rest of this tutorial, we mostly use the classic form, because you will see it in all the existing code.

print and println

public class Print {
    public static void main(String[] args) {
        System.out.print("Hello ");
        System.out.print("World");
        System.out.println("!");
        System.out.println("Next line");
    }
}
Output

Hello World!
Next line

print stays on the same line, and println goes to the next line after the text.

Common beginner mistakes

  • The class name and the file name are different (Main and main.java).
  • A missing semicolon ; at the end of a statement.
  • Writing system.out.println with a small s. Java is case sensitive.
  • A missing quote or bracket.

Here is what a missing semicolon looks like:

public class Oops {
    public static void main(String[] args) {
        System.out.println("Hello")
    }
}
Output

Oops.java:3: error: ';' expected
System.out.println("Hello")
^
1 error
error: compilation failed

Note: Read the error message from the top. It tells the file, the line number and the problem. Next: Java Syntax.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.