How do I Compile and Run a Single Java 25 Source File?

Java 25 makes running a single .java file easier than ever. Thanks to JEP 330 (Launch Single-File Source-Code Programs), combined with the new JEP 512 (Compact Source Files and Instance Main Methods), you can go from source to running program with a single command — no explicit javac step required.

Let’s walk through the options step by step.


1. Prerequisites

  • JDK 25 installed and on your PATH
  • Verify your setup:
java --version
javac --version

Both should report version 25.


2. Write a Single-File Program

Create a file called Hello.java. In Java 25, the simplest possible form is:

void main() {
    IO.println("Hello, Java 25!");
}

No class, no static, no String[] args, no imports. The IO class is auto-imported in compact source files.


3. Run It Directly (No Compilation Step)

This is the recommended approach for scripts, prototypes, and small utilities:

java Hello.java

What happens under the hood:

  1. The java launcher detects that the argument ends in .java.
  2. It invokes the compiler in memory (nothing is written to disk).
  3. The resulting bytecode is executed immediately.

Expected output:

Hello, Java 25!

Passing Arguments to Your Program

Anything after the source file name is passed as an argument to main:

java Hello.java arg1 arg2 arg3

To receive them, declare the parameter:

void main(String[] args) {
    for (String arg : args) {
        IO.println("Got: " + arg);
    }
}

4. Compile and Run Separately (Traditional Way)

If you want a reusable .class file (for example, to distribute or run repeatedly without recompiling), do it in two steps.

Step 1 — Compile

javac Hello.java

This produces Hello.class in the current directory.

Note: For a compact source file without a class declaration, the compiler generates a synthetic class name based on the file name.

Step 2 — Run

java Hello

Note there is no .java extension here — you pass the class name, not the file name.


5. Choosing a Specific Source Version

If your default javac isn’t Java 25, you can request the level explicitly:

javac --release 25 Hello.java

Or, when running a single-file program:

java --source 25 Hello.java

This is handy if multiple JDKs coexist on your system.


6. Handling Files with a Non-Matching Name

With single-file source-code execution, the file name does not have to match any class defined inside — even if you declare public class Foo inside Bar.java, the following still works:

java Bar.java

However, if you switch to the classic two-step javac + java workflow, the standard rule applies: a public class must live in a file with the same name.


7. Adding a Shebang for Script-Like Execution (Unix/macOS)

You can turn a .java file into an executable script by adding a shebang line as the very first line:

#!/usr/bin/env java --source 25

void main() {
    IO.println("Running as a script!");
}

Then make it executable and run:

chmod +x hello
./hello

The file must not have a .java extension when using the shebang trick — otherwise the launcher tries to compile the shebang line as Java source.


8. Quick Reference

Goal Command
Run a single source file java Hello.java
Run with program arguments java Hello.java foo bar
Force a specific source level java --source 25 Hello.java
Compile only javac Hello.java
Compile with an explicit release javac --release 25 Hello.java
Run compiled class java Hello

9. Common Pitfalls

Problem Cause Fix
error: unknown source file extension You passed a file without .java to java Use java Hello.java (with extension) or java Hello (without) after compiling
error: 'class', 'interface', ...' expected Older JDK doesn’t understand compact source files Upgrade to JDK 25
main method not found Wrong signature (e.g., int main()) Use void main() or void main(String[] args)
Shebang script fails to run File has .java extension Rename the file to remove the extension

Summary

  • For quick experiments: java Hello.java — one command, no .class file produced.
  • For repeated runs or distribution: javac Hello.java then java Hello.
  • Combine with Java 25’s compact source files and instance main for the shortest possible programs.

This unified workflow makes Java feel almost script-like while keeping the full power of the platform available when you need it.

How do I Organize Multiple Methods in a Compact Source File?

Java 25 makes it easier than ever to write small, focused programs without ceremony. Thanks to JEP 512: Compact Source Files and Instance Main Methods (finalized in Java 25), you can skip the enclosing class declaration entirely and still define multiple methods and fields in a single source file. This is perfect for scripts, learning exercises, and quick utilities.

Let me walk you through the best practices for organizing methods in these compact files.


1. The Basic Structure

A compact source file has an implicit top-level class. You just write your main method (instance-style, no static required) and add helper methods around it:

void main() {
    println("Welcome!");
    greet("Alice");
    println("Sum = " + add(3, 4));
}

void greet(String name) {
    println("Hello, " + name + "!");
}

int add(int a, int b) {
    return a + b;
}

No public class Foo { ... } wrapper is needed. The compiler generates it for you.


2. Put main First (or Make It Easy to Find)

For readability, keep the entry point at the top of the file so a reader immediately sees the program’s flow:

void main() {
    var user = askName();
    var total = computeTotal(10, 20, 30);
    printReport(user, total);
}

// --- helpers below ---

String askName() {
    return "Guest";
}

int computeTotal(int... values) {
    int sum = 0;
    for (int v : values) sum += v;
    return sum;
}

void printReport(String user, int total) {
    println("User : " + user);
    println("Total: " + total);
}

This mirrors how many scripting languages read: entry point first, details after.


3. Group Related Methods Together

When your file grows, cluster methods by responsibility and separate the groups with comment banners:

void main() {
    var nums = List.of(1, 2, 3, 4, 5);
    println("Sum      = " + sum(nums));
    println("Average  = " + average(nums));
    println("Uppercase: " + shout("hello"));
}

// ---------- Math helpers ----------

int sum(List<Integer> xs) {
    return xs.stream().mapToInt(Integer::intValue).sum();
}

double average(List<Integer> xs) {
    return xs.stream().mapToInt(Integer::intValue).average().orElse(0);
}

// ---------- String helpers ----------

String shout(String s) {
    return s.toUpperCase() + "!";
}

If a group becomes large, that is a strong signal it should be extracted into its own class or file.


4. Use Instance Fields for Shared State

Compact files support instance fields, so you don’t need to pass configuration through every method call:

final String appName = "DemoApp";
final int maxRetries = 3;

void main() {
    banner();
    run();
}

void banner() {
    println("=== " + appName + " ===");
}

void run() {
    for (int i = 1; i <= maxRetries; i++) {
        println("Attempt " + i);
    }
}

Prefer final fields to keep the file predictable and easy to reason about.


5. Leverage the Auto-Imported java.base and IO Methods

Java 25 auto-imports common utilities and gives you top-level print, println, and readln (from java.lang.IO). This keeps helper methods short:

void main() {
    var name = readln("Your name: ");
    println(greeting(name));
}

String greeting(String name) {
    return "Hello, " + (name.isBlank() ? "stranger" : name) + "!";
}

No import statements, no System.out.println — the file stays compact.


6. Keep Methods Small and Single-Purpose

Because there is no class boundary to hide behind, discipline matters more. Follow these guidelines:

Guideline Why it matters in a compact file
One responsibility per method Compensates for the flat structure
Short method names, descriptive The file reads top-to-bottom like a script
Prefer pure functions Easier to reason about without a class scope
Extract when > ~15 lines Prevents the file from becoming a wall of code

7. Order Methods by “Newspaper Style”

Arrange methods so the reader moves from high-level to low-level, like a newspaper article:

void main() {           // headline: what the program does
    processOrder();
}

void processOrder() {   // section: main steps
    validate();
    charge();
    ship();
}

void validate() { /* ... */ }   // details
void charge()   { /* ... */ }
void ship()     { /* ... */ }

Readers rarely need to jump around — they simply scroll down for more detail.


8. When to Stop Using a Compact File

Compact source files shine for small, self-contained programs. Migrate to a regular class (or multiple classes) when you notice:

  • Multiple unrelated groups of methods
  • Need for multiple types (records, enums beyond simple helpers)
  • Reuse from other files
  • Unit tests targeting individual methods

You can promote a compact file by simply wrapping everything in public class Name { ... } and adding public static void main(String[] args) — the migration is mechanical.


Complete Example

Here is a compact file that puts all the tips together:

final String title = "Tip Calculator";

void main() {
    banner();
    double bill = 84.50;
    double tipPct = 0.18;

    double tip = tipAmount(bill, tipPct);
    double total = bill + tip;

    printLine("Bill",  bill);
    printLine("Tip",   tip);
    printLine("Total", total);
}

// ---------- domain logic ----------

double tipAmount(double bill, double pct) {
    return round2(bill * pct);
}

double round2(double v) {
    return Math.round(v * 100.0) / 100.0;
}

// ---------- output helpers ----------

void banner() {
    println("=== " + title + " ===");
}

void printLine(String label, double value) {
    println(String.format("%-6s: %8.2f", label, value));
}

Run it directly with:

java TipCalculator.java

Summary

  • Put main first, helpers below.
  • Group related methods and separate groups with comment banners.
  • Use instance fields for shared, mostly-final state.
  • Rely on auto-imports and top-level IO methods to stay concise.
  • Follow newspaper order — general to specific.
  • Graduate to a regular class once the file grows beyond a single concern.

Compact source files let you write real, multi-method programs with almost zero boilerplate — as long as you keep the file focused and well-organized.

How do I Read User Input in a Compact Java 25 Program?

Java 25 (via JEP 512: Compact Source Files and Instance Main Methods, finalized in Java 25) makes reading user input dramatically simpler. You no longer need a class declaration, a public static void main(String[] args) signature, or even System.out.println / Scanner boilerplate.

The New IO Class

Java 25 introduces the java.lang.IO class, which is automatically imported in compact source files. It provides three convenient static methods:

Method Purpose
IO.print(x) Print without newline
IO.println(x) Print with newline
IO.readln(prompt) Print a prompt and read a line from stdin

Compact Example

Here’s a compact Java 25 program that reads user input:

void main() {
    String username = IO.readln("Username: ");
    String password = IO.readln("Password: ");
    int result = Integer.parseInt(IO.readln("What is 2 + 2: "));

    if (username.equals("admin") && password.equals("secret") && result == 4) {
        IO.println("Welcome to Java Application");
    } else {
        IO.println("Invalid username or password, access denied!");
    }
}

Key Points

  • No class declaration required — the file becomes an implicitly declared class.
  • No String[] args — you can just write void main().
  • No import statements — java.base and java.lang.IO are auto-imported.
  • No Scanner — IO.readln(...) handles the prompt and line read in one call.
  • The method can be void main() or void main(String[] args); static is optional.

Running It

Save the code as Login.java and run it directly (no compile step needed):

java Login.java

When You Still Need Scanner

IO.readln only returns String. If you need typed input like int, double, etc., you either:

  1. Parse it yourself (as shown above with Integer.parseInt), or
  2. Fall back to java.util.Scanner for its nextInt(), nextDouble(), etc.

For most simple interactive programs, IO.readln + parsing is the cleanest approach in Java 25.

How do I Use an Instance main Method in Java 25?

Java 25 finalizes JEP 512: Compact Source Files and Instance Main Methods, which was previewed in earlier JDK releases. This feature makes Java far more approachable for beginners and reduces boilerplate for small programs and scripts.

What Changed?

Traditionally, every Java program required this ceremony:

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

With Java 25, the main method no longer needs to be:

  • public
  • static
  • Declared with a String[] args parameter

The New Rules

The JVM launcher now looks for a main method in this order of preference:

  1. static void main(String[] args) — traditional form
  2. static void main() — no parameters
  3. void main(String[] args) — instance method with args
  4. void main() — instance method, no args simplest form

If an instance main method is found, the JVM will implicitly create an instance of the enclosing class using its no-argument constructor, then invoke main on it.

Example 1: The Simplest Instance main

public class Hello {
    void main() {
        System.out.println("Hello from an instance main!");
    }
}

That’s the entire program. No static, no String[] args, no public.

Run it with:

java Hello.java

Example 2: Instance main With Fields and Helper Methods

Because main is now an instance method, it can freely use instance fields and call other instance methods without needing static everywhere:

public class Greeter {
    private final String greeting = "Hello";

    void main() {
        greet("Java 25");
        greet("Developers");
    }

    void greet(String name) {
        System.out.println(greeting + ", " + name + "!");
    }
}

Notice that greet is also a plain instance method — no static modifier needed.

Example 3: Combined With Compact Source Files

Java 25 also allows you to omit the enclosing class entirely (Compact Source File):

void main() {
    System.out.println("No class declaration required!");
}

Save this as Demo.java and run:

java Demo.java

The compiler implicitly wraps the code in a synthetic class for you.

Example 4: Instance main With Arguments

If you still need command-line arguments, just declare them:

public class Echo {
    void main(String[] args) {
        for (String arg : args) {
            System.out.println("Argument: " + arg);
        }
    }
}

Requirements & Caveats

  • The enclosing class must have an accessible no-argument constructor (the default one is fine if you don’t declare any constructor).
  • The class cannot be abstract.
  • If both a static and an instance main exist, the static one wins (per the resolution order above).
  • The instance main method cannot be private. It must be at least package-private.
  • To run a single source file directly (java Foo.java), you don’t need to compile first — the launcher handles it.

Why This Matters

  • Lower barrier for beginners — no need to explain public, static, String[] args, or classes on day one.
  • Cleaner scripts — small utilities and experiments become much more concise.
  • Smoother learning curve — students can gradually introduce classes, static, and access modifiers as they progress, rather than all at once.

Quick Comparison

Style Java ≤ 20 Java 25
public static void main(String[] args) ✅ Required ✅ Still works
static void main() ❌ ✅
void main(String[] args) ❌ ✅
void main() ❌ ✅
No class declaration ❌ ✅ (Compact Source File)

Instance main methods, combined with compact source files, make Java 25 one of the most beginner-friendly releases in the language’s history — while remaining fully backward compatible with every existing Java program.

How do I Run My First Java 25 Program Without Creating a Class?

Java 25 makes it official: you can now write and run a program without declaring a class, without public static void main(String[] args), and even without import statements for common APIs. This feature is called Compact Source Files and Instance Main Methods (JEP 512, finalized in Java 25).

Let’s walk through it step by step.

1. Prerequisites

  • JDK 25 installed and available on your PATH
  • Verify with:
java --version
javac --version

Both should report version 25.

2. Write the Program

Create a plain text file named Hello.java. That’s it — no class, no public static, no ceremony:

void main() {
    IO.println("Hello, Java 25!");
}

A few things worth noticing:

  • There is no class declaration. The compiler wraps the code in an implicitly declared class for you.
  • main is an instance method (not static) and takes no arguments (the String[] args parameter is optional now).
  • IO.println(...) comes from the new java.io.IO class, which is auto-imported in compact source files — no System.out.println and no import needed.

3. Run It Directly with java

Since JDK 11, you can run a single-file source program directly. In Java 25, this works beautifully with the new compact form:

java Hello.java

Expected output:

Hello, Java 25!

No javac step is required. The launcher compiles the file in memory and runs it.

4. A Slightly Richer Example

You can still read input, do logic, and use any Java API — just without the boilerplate:

void main() {
    var name = IO.readln("What is your name? ");
    IO.println("Welcome, " + name + "!");

    for (int i = 1; i <= 3; i++) {
        IO.println("Count: " + i);
    }
}

Run it the same way:

java Hello.java

5. When You Outgrow It

Compact source files are meant for learning, scripting, and quick experiments. When your program grows, you can gradually add:

  1. A String[] args parameter to main when you need CLI arguments.
  2. Additional methods and fields directly in the file (they become members of the implicit class).
  3. Finally, an explicit class declaration — at which point you have a regular Java source file.

The transition is smooth because the language rules are a strict superset of traditional Java.

6. Common Pitfalls

Issue Cause Fix
error: class ... is public, should be declared in a file named ... You added public to a helper class in the same file Remove public — the implicit class is unnamed
IO cannot be resolved You’re not on JDK 25 (or using an older preview flag) Upgrade to JDK 25; no --enable-preview needed anymore
main not found Wrong signature (e.g., returns int) Use void main() or void main(String[] args)

Summary

To run your first Java 25 program without creating a class:

  1. Install JDK 25.
  2. Create Hello.java containing just a void main() method.
  3. Use IO.println(...) — no imports needed.
  4. Run it with java Hello.java.

This is the shortest path from “I have JDK installed” to “my program is running” that Java has ever offered — perfect for beginners and for quick prototypes alike.