Your First Java Program: Hello World With Modern Java

Java’s Hello World now comes in two forms: the classic class-based version that every textbook shows, and the compact source file version that became standard in Java 25 (LTS). This guide shows both and explains every keyword. It also covers how to compile and run them, and the errors you will hit on day one.

Quick Takeaways

  • The classic program needs a class, a public static void main(String[] args) method, and System.out.println().
  • Since Java 25, void main() { IO.println("Hello, World!"); } is a valid complete program. No preview flag is needed.
  • Run a single file directly with java Hello.java. Skip javac for small programs.
  • Use the classic form for real projects and the compact form for learning, scripts, and quick experiments.
Approach Minimum Java Lines of code Best for
Classic class + static main 1.0 5 Production code, libraries, frameworks
Source launcher (java File.java) 11 5 Quick scripts without a separate compile step
Compact source file + instance main 25 3 Learning, prototypes, small utilities

What You Need Before Writing Code

You need a JDK (Java Development Kit), not just a JRE. The JDK includes javac (the compiler) and java (the launcher).

As of November 2026, Java 25 is the current LTS (long-term support) release. Java 27 shipped in September 2026 as a non-LTS release. Oracle’s roadmap lists Java 29 as the next LTS in September 2027. Install Java 25 or later to follow every example below.

Verify your install:

java --version
javac --version

Expected output (your build numbers will differ):

openjdk 25.0.1 2025-10-21 LTS
javac 25.0.1

If javac is not found, you installed a runtime only. Install a full JDK from Oracle, Adoptium, Amazon Corretto, or your package manager.

The Classic Java Hello World

Create a file named HelloWorld.java. The file name must match the public class name exactly, including capitalization.

// HelloWorld.java
public class HelloWorld {

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

Compile and run it:

javac HelloWorld.java   # produces HelloWorld.class (bytecode)
java HelloWorld         # starts the JVM and runs the class

Output:

Hello, World!

javac translates source code into bytecode stored in HelloWorld.class. The java command starts the JVM, loads that class, finds main, and executes it. Notice that you pass the class name to java, not the file name.

Syntax Breakdown: Every Keyword Explained

Each token in the classic program has a job. Here is what the JVM sees.

public class HelloWorld

A class is the basic unit of code in Java. public makes it visible to every other class. The compiler enforces one rule here: a public top-level class must live in a file with the same name.

public static void main(String[] args)

This is the entry point. The JVM looks for this exact signature when you run a class.

Token Meaning
public The JVM, which lives outside your class, must be able to call it.
static The method belongs to the class, so the JVM can call it without creating an object.
void The method returns nothing to the JVM.
main The fixed method name the launcher searches for.
String[] args Command-line arguments passed to the program as an array.

System.out.println("Hello, World!")

System is a built-in class in java.lang. out is a static field of type PrintStream that points at standard output. println() prints its argument and appends a line break. Because java.lang is imported automatically, you need no import statement.

Reading Command-Line Arguments

The args array is not decoration. This version greets whoever you name:

// Greeter.java
public class Greeter {

    public static void main(String[] args) {
        // Fall back to "World" when no argument is supplied
        String name = args.length > 0 ? args[0] : "World";
        System.out.println("Hello, " + name + "!");
    }
}
javac Greeter.java
java Greeter Ada

Output:

Hello, Ada!

Calling java Greeter with no argument prints Hello, World!. The ternary check on args.length prevents an ArrayIndexOutOfBoundsException.

Run a Single File Without javac

Since Java 11, the source-file mode of the launcher compiles in memory and runs immediately:

java HelloWorld.java

Output:

Hello, World!

No .class file lands on disk. This mode suits scripts and experiments. It works for classic and compact files alike. Larger projects still need a build tool such as Maven or Gradle.

Modern Java Hello World: Compact Source Files

The classic program makes beginners learn classes, access modifiers, static, arrays, and a nested field access before they print one line. JEP 512, finalized in Java 25, removes that barrier. It combines two features: compact source files and instance main methods.

Create Hello.java:

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

Run it:

java Hello.java

Output:

Hello, World!

That is the entire program. Three things changed.

  1. No class declaration. The compiler wraps your top-level methods and fields in an implicitly declared class. The class is final and takes its name from the file.
  2. No static, public, or String[] required. The launcher accepts an instance main method.
  3. IO.println() replaces System.out.println(). The new java.lang.IO class offers simple console helpers.

Java 25 finalized this feature, so you do not need --enable-preview. Earlier versions (21 through 24) required that flag.

The IO Class

java.lang.IO lives in java.lang, so it needs no import. Its static methods include print(), println(), and readln(). In compact source files you must write the class name: IO.println(...). The static methods are not implicitly imported.

This interactive example uses IO.readln() to read input:

// Ask.java
void main() {
    String name = IO.readln("What is your name? ");
    IO.println("Hello, " + name + "!");
}
java Ask.java

Sample session:

What is your name? Grace
Hello, Grace!

Before this change, the same task required importing java.util.Scanner and wrapping System.in. The IO class removes that ceremony for beginner programs.

Automatic Imports

A compact source file automatically imports every public class from packages exported by the java.base module. That includes java.util, java.io, java.time, and others. This program uses a List without an import:

// Languages.java
void main() {
    List<String> languages = List.of("Java", "Kotlin", "Scala");

    for (String language : languages) {
        IO.println("Hello from " + language + "!");
    }
}

Output:

Hello from Java!
Hello from Kotlin!
Hello from Scala!

Extra Methods and Fields

Compact source files allow top-level methods and fields. Use them to organize logic:

// Greeting.java
String greeting = "Hello";

String greet(String name) {
    return greeting + ", " + name + "!";
}

void main() {
    IO.println(greet("World"));
}

Output:

Hello, World!

The method greet and the field greeting become instance members of the hidden class. main can call them directly because it is an instance method too.

How the Launcher Picks a main Method

Modern Java supports several main signatures. The launcher checks them in a fixed priority order.

Priority Signature Notes
1 static void main(String[] args) Classic form
2 static void main() Static, no arguments
3 void main(String[] args) Instance method, needs a non-private no-arg constructor
4 void main() Instance method, no arguments

Access modifiers are optional for the newer forms. A non-private main with any of these signatures qualifies. The launcher creates an object of your class first when it selects an instance method, then calls main on it.

Classic vs. Compact: A Direct Comparison

Criteria Classic Java Compact Source File
Boilerplate High (class, modifiers, array) Minimal
Concepts needed on day one Classes, static, arrays, fields Methods and statements
Console output System.out.println() IO.println()
Multiple classes per file Yes Yes (extra classes become nested members)
Package declaration Allowed Not allowed
Fit for libraries and frameworks Yes No
Migration path Already standard Wrap the code in a class when it grows

Compact files cannot declare a package. They suit single-file programs. When a project grows, wrap your methods in a named class and add static or keep instance methods as needed. The code inside stays almost identical.

Bad Code vs. Good Code

Hello World programs teach habits. These anti-patterns appear in beginner code constantly.

Anti-pattern: Logic Crammed Into main

// Bad: HelloBad.java
public class HelloBad {
    public static void main(String[] args) {
        String n = args.length > 0 ? args[0] : "World";
        String m = "Hello, " + n + "!";
        System.out.println(m);
        System.out.println(m.toUpperCase());
        // Formatting, validation, and output are tangled together
    }
}

Problems: cryptic variable names, no reusable method, and no way to test the greeting without running the whole program.

Refactored: Extract a Pure Method

// Good: HelloGood.java
public class HelloGood {

    // Pure function: easy to unit test, no side effects
    static String buildGreeting(String name) {
        return "Hello, %s!".formatted(name);
    }

    public static void main(String[] args) {
        String name = args.length > 0 ? args[0] : "World";
        System.out.println(buildGreeting(name));
    }
}

Output with no arguments:

Hello, World!

String.formatted() (Java 15+) replaces manual concatenation. The extracted buildGreeting method returns a value, so a unit test can assert on it.

Anti-pattern: File Name Does Not Match the Class

// Saved as hello.java (lowercase)
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

javac rejects this. Rename the file to HelloWorld.java or remove public from the class.

Common Errors and Fixes

Error message Cause Fix
class HelloWorld is public, should be declared in a file named HelloWorld.java File name differs from the public class name Rename the file to match exactly
error: ';' expected Missing semicolon Add ; at the end of the statement
Error: Could not find or load main class HelloWorld Wrong directory, or you typed java HelloWorld.class Run java HelloWorld from the folder holding the .class file
Error: Main method not found in class HelloWorld Wrong main signature (for example Main or missing String[] in a classic class) Use public static void main(String[] args)
'javac' is not recognized JDK missing or not on PATH Install a JDK and add its bin folder to PATH
cannot find symbol: variable system Typed system instead of System Java is case-sensitive; capitalize System
cannot find symbol: method println on IO Called println(...) without IO. in a compact file Write IO.println(...)

Running on an Older JDK

On Java 21 through 24, compact source files exist only as a preview feature. Enable them explicitly:

java --enable-preview --source 21 Hello.java

Use the matching release number for --source. Preview APIs also change between releases. Java 21 and 22 used System.out.println in compact files, and the IO class arrived later. For anything you plan to keep, upgrade to Java 25. Use the classic form if you must stay on an older runtime.

Where to Go After Hello World

Once the program runs, build these skills in order:

  1. Variables and types: int, double, boolean, String, and the var keyword for local type inference.
  2. Control flow: if, switch expressions, for, and enhanced for loops.
  3. Methods and classes: parameters, return values, constructors, and records for simple data holders.
  4. Collections: List, Map, and Set with the Streams API.
  5. Build tools: a Maven or Gradle project once you have more than a handful of files.

Each step adds one concept at a time, which is exactly the learning path the compact-file feature was designed to support.

FAQ

Why is main declared public static void in classic Java?

The JVM calls main from outside your class before any object exists. public gives the JVM access, static lets it call the method without creating an instance, and void means the method returns no value. Since Java 25, an instance method named main also works, and the launcher creates the object for you.

Do I need to compile a Java program before running it?

Not always. Run java Hello.java and the launcher compiles the file in memory and runs it. This source-file mode works since Java 11. A separate javac step is still the normal route for multi-file projects, and build tools handle it for you.

What is IO.println() in Java?

IO.println() is a static method of java.lang.IO, added as a final feature in Java 25. It prints a value and a newline to standard output. It is a shorter alternative to System.out.println() and is designed mainly for beginner and compact-source-file programs.

Can I still use System.out.println() in Java 25?

Yes. System.out.println() works in every Java version and in every kind of file, including compact source files. Production code, logging frameworks, and libraries continue to rely on it or on a logger.

Hot this week

Memory Management Across Languages: C++, Java, Python, and JavaScript

Compare manual allocation, garbage collection, and reference counting in C++, Java, Python, and JavaScript. See code and fix leaks today.

JavaScript Operators, Type Coercion, and == vs ===

Master JavaScript operators, type coercion rules, and == vs === with code examples, comparison tables, and fixes. Write safer comparisons today.

Common Python Beginner Mistakes (and How to Avoid Them)

Avoid the 10 most common Python beginner mistakes, from mutable defaults to bare except. Learn the fixes with code examples and start coding cleaner.

Dart Null Safety, Records, and Pattern Matching Explained

Master Dart 3 null safety, records, and pattern matching with production-ready code, comparison tables, and refactors. Start writing safer Dart today.

std::print and std::format: Modern C++ Output

Learn std::print and std::format in C++23: syntax, format specs, custom formatters, and migration from printf and iostream. Copy the examples now.

Topics

Memory Management Across Languages: C++, Java, Python, and JavaScript

Compare manual allocation, garbage collection, and reference counting in C++, Java, Python, and JavaScript. See code and fix leaks today.

JavaScript Operators, Type Coercion, and == vs ===

Master JavaScript operators, type coercion rules, and == vs === with code examples, comparison tables, and fixes. Write safer comparisons today.

Common Python Beginner Mistakes (and How to Avoid Them)

Avoid the 10 most common Python beginner mistakes, from mutable defaults to bare except. Learn the fixes with code examples and start coding cleaner.

Dart Null Safety, Records, and Pattern Matching Explained

Master Dart 3 null safety, records, and pattern matching with production-ready code, comparison tables, and refactors. Start writing safer Dart today.

std::print and std::format: Modern C++ Output

Learn std::print and std::format in C++23: syntax, format specs, custom formatters, and migration from printf and iostream. Copy the examples now.

Value Types vs Reference Types in C#: A Visual Guide

Learn how C# value types and reference types differ in memory, copying, and equality. Stack vs heap diagrams and code examples. Read the guide.

JavaScript Data Types: Primitives, Objects, and typeof

Learn all 8 JavaScript data types, how primitives differ from objects, and how typeof works, with code examples. Read the full guide now.

Variables in JavaScript: let, const, and Why var Is Legacy

Learn how let, const, and var differ in JavaScript: scope, hoisting, and the TDZ. See why var is legacy and refactor your code today.

Related Articles

Popular Categories