Vertical Whitespace

A single blank line appears:

  • after package statement;
  • before imports;
  • after imports;
  • around class;
  • after class header;
  • around field in interface;
  • around method in interface;
  • around method;
  • around initializer;
  • as required by other sections of this document.

Multiple blank lines are not permitted.

Horizontal whitespace

Beyond where required by the language or other style rules, and apart from literals, comments and Javadoc, a single ASCII space also appears in the following places only.

  1. Separating any reserved word, such as if, for, while, switch, try, catch or synchronized, from an open parenthesis (() that follows it on that line
  2. Separating any reserved word, such as else or catch, from a closing curly brace (}) that precedes it on that line
  3. Before any open curly brace ({), with two exceptions:

    • @SomeAnnotation({a, b}) (no space is used)
    • String[][] x = {{"foo"}}; (no space is required between {{, by item 8 below)
  4. On both sides of any binary or ternary operator. This also applies to the following "operator-like" symbols:

    • the ampersand in a conjunctive type bound: <T extends Foo & Bar>
    • the pipe for a catch block that handles multiple exceptions: catch (FooException | BarException e)
    • the colon (:) in an enhanced for ("foreach") statement
    • the arrow in a lambda expression: (String str) → str.length()

      but not:

    • the two colons (::) of a method reference, which is written like Object::toString
    • the dot separator (.), which is written like object.toString()
  5. After ,:; or the closing parenthesis ()) of a cast
  6. Between the type and variable of a declaration: List<String> list
Horizontal alignment: never required

Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.

This practice is permitted, but is never required. It is not even required to maintain horizontal alignment in places where it was already used.