Fundamentals 28 min read

Master Google’s Java Style Guide: Essential Formatting Rules for Clean Code

This article presents Google’s official Java coding style guide, covering terminology, file naming, source‑file structure, formatting rules such as brace placement, indentation, line length, whitespace, naming conventions, Javadoc standards, and practical programming recommendations to help developers write consistent, readable Java code.

21CTO
21CTO
21CTO
Master Google’s Java Style Guide: Essential Formatting Rules for Clean Code

Google Official Java Programming Style Guide

The guide discusses not only visual formatting but also conventions and coding standards. It focuses on commonly‑followed rules and avoids prescribing opinions for non‑mandatory items.

1.1 Terminology

The term class can refer to a regular class, enum, interface, or annotation type ( @interface).

The term comment refers only to implementation comments; documentation comments are called Javadoc.

1.2 Guide Description

Example code illustrates the style but does not define the only way to write code; formatting choices in examples are not mandatory rules.

Source File Basics

2.1 File Name

Source files are named after their top‑level class, case‑sensitive, with the .java extension.

2.2 File Encoding

All source files use UTF‑8 encoding.

2.3 Special Characters

2.3.1 Whitespace Characters

The only whitespace character allowed in source files (aside from line‑ending sequences) is the ASCII space (0x20). All other whitespace must be escaped, and tabs are not used for indentation.

2.3.2 Escape Sequences

Characters with special escape sequences ( \b, \t, \n, \f, \r, \", \') must be written using their escape forms, not octal or Unicode escapes.

2.3.3 Non‑ASCII Characters

Use either the actual Unicode character (e.g., ∞) or its Unicode escape ( \u221e) whichever improves readability. Add comments when using Unicode escapes.

Source File Structure

A source file contains (in order):

License or copyright information (if needed)

Package statement

Import statements

Exactly one top‑level class (or package‑info.java which may lack a class)

3.1 License / Copyright

If present, place it at the very beginning of the file.

3.2 Package Statement

The package statement must be on a single line; column limits do not apply.

3.3 Import Statements

3.3.1 No Wildcards

Do not use wildcard imports such as import java.util.*;.

3.3.2 No Line Breaks

Each import statement occupies its own line.

3.3.3 Order and Spacing

Group imports as follows, separated by a blank line:

Static imports

Imports from com.google (if the file is under that package)

Third‑party packages, each top‑level package in alphabetical order (e.g., android, com, junit, org, sun) java imports javax imports

Within a group, maintain alphabetical order without blank lines.

3.4 Class Declaration

3.4.1 One Top‑Level Class

Each top‑level class resides in a file with the same name (including .java), except for package‑info.java which may lack a class.

3.4.2 Member Order

Order members logically; do not always append new methods at the end. Group related members together and keep the ordering explainable.

3.4.2.1 Overloads: Never Separate

When a class has multiple constructors or overloaded methods, keep them together without interleaving other members.

Formatting

4.1 Braces

4.1.1 Always Use Braces

Even for single statements (or empty blocks), always include braces with if, else, for, do, while.

4.1.2 Non‑Empty Blocks: K&R Style

Follow Kernighan & Ritchie style (Egyptian brackets): no line break before the opening brace, line break after it, line break before the closing brace, and line break after the closing brace unless it is followed by else or a comma.

4.1.3 Empty Blocks: Compact Form

An empty block can be written as {} without line breaks, except when it is part of a multi‑statement construct (e.g., if/else or try/catch/finally) where the closing brace must be on a new line.

4.2 Indentation

Use two spaces for each new block level. Indentation applies to code and comments alike.

4.3 One Statement per Line

Terminate each statement with a line break.

4.4 Column Limit

Choose either 80 or 100 characters per line. Exceptions include long URLs in Javadoc, package/import statements, and command‑line snippets in comments.

4.5 Automatic Line Wrapping

When a line exceeds the column limit, break it at a higher syntactic level. Prefer breaking before non‑assignment operators, after assignment operators, keep method names with the opening parenthesis, and keep commas with the preceding token.

4.5.2 Indent Wrapped Lines by At Least Four Spaces

Each continuation line must be indented at least four spaces beyond the first line; deeper nesting adds additional indentation.

4.6 Whitespace

4.6.1 Vertical Whitespace

Insert a blank line between consecutive class members (fields, constructors, methods, nested classes, static/instance initializer blocks) and between logical groups of statements inside methods.

4.6.2 Horizontal Whitespace

Use a single ASCII space in specific places: between keywords and following left parentheses, between a right brace and following else / catch, before left braces (except in annotations), around binary and ternary operators, after commas, colons, semicolons, and after // comment markers.

4.6.3 Horizontal Alignment

Do not require aligning code with variable numbers of spaces; alignment is optional and not enforced.

4.7 Parentheses for Grouping

Keep parentheses that clarify precedence unless all reviewers agree they are unnecessary.

4.8 Specific Structures

4.8.1 Enum Classes

Enum constants are separated by commas; line breaks are optional. Enums without methods or Javadoc can be written as array‑initialization style.

4.8.2 Variable Declarations

4.8.2.1 One Variable per Declaration

Avoid combined declarations such as int a,b;.

4.8.2.2 Declare When Needed and Initialize Promptly

Declare local variables at first use and initialize them immediately or as soon as possible.

4.8.3 Arrays

4.8.3.1 Block‑Style Initialization

Array initializers may be written as block structures; both compact and expanded forms are acceptable.

4.8.3.2 Non‑C‑Style Declarations

The brackets belong to the type: String[] args, not String args[].

4.8.4 Switch Statements

4.8.4.1 Indentation

Switch blocks are indented two spaces; each case label starts a new line indented two spaces, followed by its statements.

4.8.4.2 Fall‑Through Comments

If a case falls through, add a comment such as // fall through unless the block ends with break, continue, return, or throws an exception.

4.8.4.3 Default Case Must Appear

Every switch must contain a default block, even if empty.

4.8.5 Annotations

Annotations appear on their own line after the documentation block and apply to classes, methods, or constructors. Multiple annotations for a field may share the same line. Parameter and local‑variable annotations have no specific rules.

4.8.6 Comments

4.8.6.1 Block Comment Style

Block comments share the same indentation as surrounding code. Use /* ... */ or // .... For multi‑line block comments, each subsequent line starts with * aligned with the opening asterisk.

4.8.7 Modifiers

When present, modifiers follow the order recommended by the Java Language Specification.

Naming Conventions

5.1 General Rules

Identifiers consist only of ASCII letters and digits ( \w+). Google‑specific prefixes/suffixes (e.g., name_, mName, s_name, kName) are not used in Java.

5.2 Identifier‑Specific Rules

5.2.1 Package Names

All lower‑case, concatenated without underscores.

5.2.2 Class Names

UpperCamelCase; typically nouns or noun phrases. Interfaces may be adjectives.

5.2.3 Method Names

lowerCamelCase; usually verbs or verb phrases. JUnit test methods may contain underscores to separate logical components (e.g., testPop_emptyStack).

5.2.4 Constant Names

CONSTANT_CASE, all caps with underscores. Only true constants (static final fields that never change) use this style.

5.2.5 Non‑Constant Fields

lowerCamelCase; typically nouns or noun phrases.

5.2.6 Parameter Names

lowerCamelCase; avoid single‑character names unless for temporary or loop variables.

5.2.7 Local Variable Names

lowerCamelCase; abbreviations are allowed but avoid single characters.

5.2.8 Type Variable Names

Either a single uppercase letter (optionally followed by a digit) or an UpperCamelCase name ending with T (e.g., RequestT).

5.3 CamelCase Conversion

Convert prose to ASCII, split on spaces or punctuation, lowercase all letters, capitalize the first letter of each word for UpperCamelCase (or all but the first for lowerCamelCase), then concatenate.

Example: "Müller’s algorithm" → "MuellersAlgorithm" (UpperCamelCase) → "muellersAlgorithm" (lowerCamelCase)

Programming Practices

6.1 @Override: Use Whenever Possible

Apply the @Override annotation to any legal overriding method.

6.2 Caught Exceptions: Do Not Ignore

Handle caught exceptions appropriately (log, rethrow as AssertionError, or comment why no action is taken). In tests, an exception named expected may be ignored.

6.3 Static Members: Call via Class

Reference static members using the class name, not an instance.

6.4 Finalizers: Disable

Avoid overriding Object.finalize. If absolutely necessary, read Effective Java §7 and still avoid using it.

Javadoc

7.1 Format

7.1.1 General Form

Use the standard multi‑line Javadoc block or a single‑line form when the content fits on one line without tags.

7.1.2 Paragraphs

Separate paragraphs with a blank line. Each paragraph after the first begins with <p> without a space before the first word.

7.1.3 Javadoc Tags

Standard tags appear in the order: @param, @return, @throws, @deprecated. Descriptions must not be empty and should be indented at least four spaces if they wrap.

7.2 Summary Sentence

Each class or member starts with a concise summary fragment (a noun or verb phrase, not a full sentence). It appears in indexes and should be clear without starting with A{@code Foo} is... or This method returns....

7.3 When to Use Javadoc

All public classes and their public/protected members should have Javadoc, except for obvious methods (e.g., simple getters) and overridden methods where the superclass documentation suffices. For non‑public APIs, include Javadoc if it defines overall purpose.

Edited by: Keke (Technical New Express) Source: https://google.github.io/styleguide/javaguide.html
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSoftware EngineeringGooglecoding style
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.