JaJava · Lesson 1 of 9

Hello, World!

The famous Java Hello World. Note: it requires a class. And the class name must match the file name. And everything is public static void. Java is very thorough.

In Java, all code must be inside a class. The entry point is a static method called main. The full signature — public static void main(String[] args) — is required exactly. Welcome to Java.

Java
// File: HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Compile with javac HelloWorld.java, then run with java HelloWorld. Java 11+ added the ability to run single-file programs directly: java HelloWorld.java. The JVM (Java Virtual Machine) runs the compiled bytecode — this is the "run anywhere" part.

Java
public class HelloWorld {
    public static void main(String[] args) {
        // println adds newline; print does not
        System.out.println("Hello, World!");
        System.out.print("No newline");
        System.out.print(" here
");

        // Formatted output (like printf)
        System.out.printf("Name: %s, Age: %d%n", "Alice", 30);

        // String.format — returns a string
        String msg = String.format("Pi is %.4f", 3.14159);
        System.out.println(msg);

        // Command-line arguments
        if (args.length > 0) {
            System.out.println("First arg: " + args[0]);
        }

        // Modern Java (21): text blocks
        String json = """
                {
                    "name": "Alice",
                    "age": 30
                }
                """;
        System.out.println(json);
    }
}
◆ Note
Java file names must exactly match the public class name, including case. HelloWorld.java must contain public class HelloWorld. This is a compile-time error if they don't match.