Skip to content

Java Formatter

Paste a Java class, record, interface or enum to get consistently indented code with sensible line breaks.

Input
Formatted Java

    
Ready

Last reviewed:

What is Java code formatting?

The Java compiler ignores whitespace between tokens, so a class can be written on one line or spread over hundreds and compile identically. People are not so forgiving: consistent indentation, spacing around operators, one statement per line and predictable line breaks in long method chains make code faster to read and review. Most teams agree a style once and apply it automatically, rather than arguing about it in every pull request.

Several conventions exist. The original Code Conventions for the Java Programming Language from Sun (1997) used four-space indentation. The Google Java Style Guide uses two spaces and a 100-column limit. Many companies use their IDE's default formatter, typically four spaces in IntelliJ IDEA and Eclipse. What matters most is that every file in a project follows the same rules, so diffs show only real changes.

This tool uses Prettier with prettier-plugin-java, an opinionated formatter that parses your code into a syntax tree and prints it from scratch. Your original layout does not affect the result, so the same code always comes out the same way. It understands modern Java, including records, switch expressions, lambdas, text blocks, var and sealed types.

How to use this tool

  1. Paste Java code into Input or click Paste. A full file with package and imports, a single class, or a fragment such as a few statements all work. Sample loads a compressed Spring-style service class.
  2. Choose an indent of 4 spaces, 2 spaces or Tab, and a line width of 80, 100 or 120 columns (120 is the default). Long expressions and method chains are broken across lines when they exceed the width.
  3. With Format as I type on, the output updates as you edit; otherwise click Format.
  4. If the code cannot be parsed, the status line says it is not valid Java and suggests looking for a missing semicolon, brace or parenthesis.
  5. Click Copy, or Download to save Formatted.java. Rename the file to match your public class before compiling.

Examples

A compressed class

Input:

public class Greeter{private final String name;public Greeter(String name){this.name=name;}public String greet(int times){StringBuilder sb=new StringBuilder();for(int i=0;i<times;i++){sb.append("Hello, ").append(name).append("! ");}return sb.toString().trim();}}

Output with 4 spaces:

public class Greeter {

    private final String name;

    public Greeter(String name) {
        this.name = name;
    }

    public String greet(int times) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < times; i++) {
            sb.append("Hello, ").append(name).append("! ");
        }
        return sb.toString().trim();
    }
}

The append chain fits within the width, so it stays on one line. Prettier also adds a blank line at the start of the class body.

A long stream pipeline at 80 columns

class A {

    List<String> names(List<User> users) {
        return users
            .stream()
            .filter(u -> u.isActive() && u.getAge() >= 18)
            .map(User::getName)
            .sorted()
            .collect(Collectors.toList());
    }
}

The input was a single line. Because the chain is longer than 80 columns, each call goes on its own line, which also makes each step easy to comment out or review.

Switch expressions and records

class A {

    String label(Order o) {
        return switch (o.status()) {
            case "PAID" -> "Paid";
            case "SHIPPED" -> "On its way";
            default -> "Pending";
        };
    }

    record Point(int x, int y) {}
}

Java 14+ switch expressions keep one case per line, and an empty record body is written as {}.

Common errors and how to fix them

  • "This is not valid Java" with a missing semicolon. int x=1} needs int x = 1;. Check the line before the place where things look wrong; the parser often notices the problem one token later.
  • Unbalanced braces. A method or class missing its closing } fails to parse. Count braces, or format smaller pieces until you find the one that breaks.
  • Unterminated string. "abc; swallows the rest of the line. Close the quote, and use a text block (""") for multi-line strings.
  • Pasted code with line numbers or diff markers. Lines starting with 12: or + from a diff are not Java. Remove them before formatting.
  • Code that is not Java. Kotlin, Groovy (as used in many Gradle build files) and JSP fragments look similar but do not parse. The formatter accepts standard Java syntax only.
  • Output looks different from your IDE. Prettier's style is fixed, including the blank line at the start of class bodies. If your project uses an IDE or Google Java Format style, format with that tool before committing so the styles do not fight.

When developers use this

  • Reading minified or machine-generated Java, such as decompiled classes or code from generators.
  • Cleaning up a snippet from Stack Overflow, a chat message or a log before adding it to a project.
  • Formatting code examples for documentation, blog posts or a pull request description.
  • Reviewing a class from someone who does not have a formatter configured.
  • Checking whether a suspicious fragment is valid Java syntax at all.

Privacy and how it works

Prettier and the Java plugin run entirely in your browser. Your code is not uploaded, stored or compiled anywhere, which matters for proprietary source code, internal class names and any credentials accidentally left in a snippet.

Limitations

  • Only formatting is done. The tool does not compile code, report type errors, organise imports or apply checks such as Checkstyle.
  • The style is Prettier's and cannot be switched to Google Java Style or IntelliJ defaults; only the indent and line width are configurable.
  • Comments are kept but are not reflowed, and very long string literals are never split.

FAQ

Does formatting change how my code behaves?

No. Only whitespace and line breaks between tokens change, and comments are kept. Text blocks may be re-indented, but Java strips that incidental indentation, so the string values are the same.

Should Java use 2 or 4 spaces?

Both are common. Four spaces is the traditional Java convention and the default in most IDEs; Google's style guide uses two. Follow your project's existing files.

Can I format just a method or a few lines?

Yes. Fragments such as a single statement or method are accepted. A fragment that refers to undeclared variables still formats, because the tool checks syntax, not types.

Which Java versions are supported?

Modern syntax through recent Java releases is supported, including records, switch expressions, pattern matching, text blocks, var and sealed classes. Very new preview features may not parse until the plugin adds them.

Are comments and Javadoc kept?

Yes. Line comments, block comments and Javadoc stay in place. Their text is not rewrapped.

Why does the output start class bodies with a blank line?

That is part of prettier-plugin-java's style, which separates the class declaration from its members. It is purely cosmetic.

How is this different from Google Java Format?

Both are opinionated formatters that ignore your existing layout. Google Java Format follows Google's style guide with two-space indentation and a 100-column limit; Prettier has its own rules and lets you choose the indent and width here.

Guides