Skip to content

Java formatting conventions teams can agree on

By · Java Developer Tools · 4 min read · Published

Every Java team eventually argues about formatting: two spaces or four, braces on the same line or the next, how long a line may be, where to break a long method chain. The arguments are rarely about correctness and almost always cost more time than the choice is worth. This guide summarises the established conventions, explains the trade-offs that actually matter, and shows how to make formatting automatic so code reviews can focus on logic.

The established style guides

Two style guides cover most Java code in the wild:

  • Google Java Style: 2-space indentation, 4-space continuation indent, a 100-column limit, and precise rules for wrapping. The google-java-format tool implements it with no configuration options at all.
  • Oracle (Sun) Code Conventions: published in 1997 and no longer maintained, but their spirit lives on in the defaults of IntelliJ IDEA and Eclipse: 4-space indentation and, in modern practice, 120 columns.

Both agree on far more than they disagree on, and both are fine. The best convention is the one your whole codebase follows consistently.

Indentation

Use spaces, not tabs, so code looks the same in every editor, diff tool and code review interface. Choose either 2 or 4 spaces per level. Four is more common in Java and makes nesting obvious; two leaves more room on each line, which matters with deeply nested lambdas and builders. Continuation lines, the second and later lines of a wrapped statement, are usually indented by twice the normal indent so they are not confused with a new block.

Braces

Java code almost universally uses the "Egyptian" or K&R style, with the opening brace at the end of the line:

if (order.isPaid()) {
    ship(order);
} else {
    remind(order.customer());
}

Always use braces, even for single-statement if, for and while bodies. Omitting them invites the classic bug where a second statement is added at the same indentation but runs unconditionally.

Line length and wrapping

A limit of 100 or 120 characters lets reviewers read code side by side without horizontal scrolling. More important than the exact number is how long lines are broken:

  • Break before operators such as +, && and ?, so the start of each continuation line shows how it connects to the previous one.
  • Break before the dot in method chains, one call per line, which is especially readable for streams and builders:
List<String> emails = customers.stream()
        .filter(Customer::isActive)
        .map(Customer::email)
        .sorted()
        .toList();
  • Break after the opening parenthesis of a long parameter list, placing each argument on its own line when they do not fit together.

Blank lines and ordering

Separate methods with one blank line, and use single blank lines inside methods to separate logical steps. Within a class, a common order is: static fields, instance fields, constructors, then methods grouped by functionality rather than by visibility. Keep overloaded methods together. Consistency here matters more than the specific order chosen.

Imports

Import ordering is a surprisingly frequent source of noisy diffs, because different IDEs sort imports differently. Agree on:

  • No wildcard imports. import java.util.* hides where names come from and can cause ambiguity when a new class with the same name is added to another package. Configure your IDE's "class count to use import with *" setting to a high number such as 999.
  • A fixed order. Google style puts all static imports in one block, then all non-static imports, each sorted in ASCII order. Whatever the order, let the formatter apply it.
  • No unused imports. They are noise and some build configurations treat them as errors.

Modern Java syntax

Newer language features have their own formatting norms:

  • Records put components on one line when short, and one per line when long, like method parameters.
  • Switch expressions with arrow labels put each case on its own line: case PAID -> "Paid";.
  • Text blocks are indented with the surrounding code; the closing """ position controls how much indentation is stripped from the content.
  • Lambdas stay on one line when short; longer bodies get braces and a normal block layout.

Older formatters can choke on these constructs, so make sure your tool supports the Java version you target.

Make formatting automatic

Conventions written in a wiki drift. Conventions enforced by a tool do not. A typical setup:

  1. Choose a formatter. google-java-format or palantir-java-format for an opinionated, configuration-free result, or a shared Eclipse formatter profile if you need custom rules. Prettier with prettier-plugin-java is an option in polyglot repositories.
  2. Run it in the build. The Spotless plugin for Maven and Gradle can check formatting (spotlessCheck) in CI and fix it locally (spotlessApply).
  3. Configure editors to match. Share an .editorconfig file for indentation and line endings, and install the formatter's IDE plugin so code is formatted on save.
  4. Reformat once, in isolation. When adopting a formatter, reformat the whole codebase in a single commit with no other changes, and add that commit's hash to .git-blame-ignore-revs so git blame skips it.

What formatting does not cover

A formatter decides layout, not quality. Naming, method length, class design and comments still need human judgement and review. Static analysis tools such as Checkstyle, PMD, SpotBugs and Error Prone can enforce some of those rules, but keep formatting and linting separate: the formatter fixes things automatically, while linters report issues for people to address.

Formatting code outside your project

Snippets pasted from tickets, chat or documentation often arrive with broken indentation. The Java Formatter formats a complete class, record, interface or enum with your choice of indentation and line width, directly in the browser. If you are writing data classes from scratch, generating them from a JSON sample with JSON to Java and then formatting the result is usually faster than typing them.