Java Code Formatter

Paste a class, a whole file or just a method and choose between two well-known Java styles. Both formatters run locally, and parse errors point at the line that broke.

Input

Settings

History

Load from URL

Two styles, two engines

The Style option switches between two separate formatters rather than two settings of one.

Prettier Java (the default) is prettier-plugin-java, the Java plugin for Prettier. It follows the toolbar’s Indent setting, which starts at 4 spaces for Java, wraps at 80 columns, and puts each argument of a long call on its own line with the closing parenthesis on a new line, the same way Prettier formats JavaScript. It also inserts a blank line after a class’s opening brace. Teams that already use Prettier for a TypeScript front end often pick it so both halves of a repository look alike.

google-java-format is Google’s own formatter, compiled to WebAssembly. It implements the Google Java Style Guide and has no knobs: indentation is always 2 spaces, continuation lines get 4, and the column limit is 100, so the toolbar’s Indent choice has no effect. Long method chains break before each dot. It is the style enforced by many Gradle and Maven plugins such as Spotless, so pick it if your build already checks for it.

Imports, snippets and other differences

Both styles sort the import block, but google-java-format goes further and deletes imports the file never uses, just like its command-line tool. Prettier Java keeps every import you wrote.

The two parsers also disagree on what counts as valid input. Prettier Java accepts fragments: a lone method, a field or a single statement such as a System.out.println call all format fine, which is convenient for code copied out of a stack trace or a tutorial. google-java-format needs a real compilation unit and stops with “class, interface, enum, or record expected” on anything less, so wrap a fragment in class Snippet { ... } before switching styles.

Modern syntax works in both: records, sealed interfaces, switch expressions with arrow labels, pattern matching for instanceof, var and text blocks. Text blocks are handled differently, though. Prettier Java keeps the opening triple quote on the same line as the assignment, while google-java-format moves it to the next line and re-indents the block.

How to format Java here

Paste the source or drop a .java file in. Detection looks for a class, interface, record or enum declaration together with something unmistakably Java, such as import java., @Override or a package com.example; line. Pick a Style, then use Ctrl/Cmd+Enter to format. Ctrl/Cmd+K opens the command palette, where typing “2 spaces” changes the indentation for Prettier Java without reaching for the mouse. Nothing is uploaded, so proprietary service code and the connection strings people tend to leave in it stay on your machine.

Keeping a block as written

Prettier Java honours // prettier-ignore on the line before a declaration or statement, and it skips everything between // @formatter:off and // @formatter:on, the markers Eclipse and IntelliJ also use. Hand-aligned lookup tables and matrices are the usual reason to reach for them. google-java-format has no equivalent, so ignored regions only work with the Prettier Java style.

Examples

Spring controller in google-java-format

The Optional chain breaks before each dot with a 4-space continuation indent, as the Google style guide prescribes.

Input
@RestController
@RequestMapping("/api/orders")
public class OrderController{private final OrderService service;public OrderController(OrderService service){this.service=service;}
@GetMapping("/{id}") public ResponseEntity<OrderDto> get(@PathVariable String id){return service.find(id).map(ResponseEntity::ok).orElseGet(()->ResponseEntity.notFound().build());}}
Output
@RestController
@RequestMapping("/api/orders")
public class OrderController {
  private final OrderService service;

  public OrderController(OrderService service) {
    this.service = service;
  }

  @GetMapping("/{id}")
  public ResponseEntity<OrderDto> get(@PathVariable String id) {
    return service
        .find(id)
        .map(ResponseEntity::ok)
        .orElseGet(() -> ResponseEntity.notFound().build());
  }
}
Open this example in the tool

Records and a switch expression with Prettier Java

Imports are sorted, each switch arm gets its own line, and the stream pipeline is split to fit 80 columns.

Input
package com.example.billing;
import java.util.List;
import java.math.BigDecimal;
public class Invoices{public record Line(String sku,int qty,BigDecimal unitPrice){}
public enum Status{DRAFT,SENT,PAID}
public static String label(Status s){return switch(s){case DRAFT->"Draft";case SENT->"Awaiting payment";case PAID->"Paid";};}
public static BigDecimal total(List<Line> lines){return lines.stream().map(l->l.unitPrice().multiply(BigDecimal.valueOf(l.qty()))).reduce(BigDecimal.ZERO,BigDecimal::add);}}
Output
package com.example.billing;

import java.math.BigDecimal;
import java.util.List;

public class Invoices {

    public record Line(String sku, int qty, BigDecimal unitPrice) {}

    public enum Status {
        DRAFT,
        SENT,
        PAID,
    }

    public static String label(Status s) {
        return switch (s) {
            case DRAFT -> "Draft";
            case SENT -> "Awaiting payment";
            case PAID -> "Paid";
        };
    }

    public static BigDecimal total(List<Line> lines) {
        return lines
            .stream()
            .map(l -> l.unitPrice().multiply(BigDecimal.valueOf(l.qty())))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
Open this example in the tool

A method copied on its own

Prettier Java formats a bare method without a surrounding class, here with 2-space indentation instead of the default 4.

Input
public Optional<Customer> findByEmail(String email){if(email==null||email.isBlank()){return Optional.empty();}return customers.stream().filter(c->c.email().equalsIgnoreCase(email)).findFirst();}
Output
public Optional<Customer> findByEmail(String email) {
  if (email == null || email.isBlank()) {
    return Optional.empty();
  }
  return customers
    .stream()
    .filter(c -> c.email().equalsIgnoreCase(email))
    .findFirst();
}
Open this example in the tool

Common errors and how to fix them

ErrorCauseFix
Failed to parse: (program (class_declaration ... (MISSING "}")))Prettier Java reached the end of the input with a class or method still open. The parse tree in the message shows where the closing brace was expected.Add the missing } and check that every method body is closed before the class ends.
Failed to parse: (program ... (MISSING ";"))A statement or field declaration is missing its semicolon, as in int x = 1 }.Add the semicolon at the end of the statement shown in the parse tree.
1:1: error: class, interface, enum, or record expectedgoogle-java-format was given a fragment, such as a single statement or method, instead of a full source file.Switch Style to Prettier Java, which accepts fragments, or wrap the code in a class declaration.
1:20: error: ';' expectedThe google-java-format parser found a declaration or statement without a terminating semicolon at that line and column.Insert the semicolon at the position reported.
1:23: error: reached end of file while parsingWith google-java-format selected, the file ended inside an unclosed block, usually a missing closing brace.Balance the braces; your editor or the bracket matching in the input pane will show which one is unpaired.

Frequently asked questions

Which style should I choose?

Use google-java-format if your build runs Spotless or the google-java-format plugin, or if your team follows the Google Java Style Guide. Choose Prettier Java if you already format the rest of the repository with Prettier.

Why does the Indent setting not change google-java-format output?

google-java-format has a fixed style: 2-space indentation, 4-space continuations and a 100-column limit. Only Prettier Java follows the Indent setting.

Does the formatter remove unused imports?

google-java-format does, and it also sorts what remains. Prettier Java sorts imports but leaves unused ones in place.

Can it format Java 21 code?

Yes for the common modern features: records, sealed types, switch expressions, pattern matching and text blocks all parse with both styles.

Does it compile or type-check my code?

No. Both formatters only parse the syntax, so missing classes, wrong types and unresolved symbols go unnoticed.

Related tools