Master Google’s Java Style Guide: Essential Rules for Clean Code
This document defines the complete Google Java Style Guide, detailing file naming, structure, formatting, naming conventions, and best‑practice recommendations—including whitespace, braces, imports, annotations, Javadoc, and exception handling—to ensure Java source files conform to Google’s coding standards.
Source File Basics
This document is the complete definition of the Google Java Style Guide. A Java source file is considered to follow Google’s Java style only when it complies with all the rules in this document.
Like other style guides, this one is not just about visual formatting; it also covers conventions and coding standards. However, the document focuses on rules that are widely enforced and avoids giving opinions on non‑mandatory items.
1.1 Terminology
The term class may refer to a regular class, an enum, an interface, or an annotation type ( @interface).
The term comment refers only to implementation comments; the term “documentation comments” is not used—instead we use Javadoc.
Other terminology is introduced later in the document.
1.2 Guide Scope
Example code in this document is not normative. Although the examples follow Google style, they do not represent the only way to write the code, and formatting choices in examples are not enforced as rules.
Source File Basics
2.1 File Name
A source file is named after its top‑level class, case‑sensitive, with the .java extension.
2.2 File Encoding: UTF‑8
Source files must be encoded in UTF‑8.
2.3 Special Characters
2.3.1 Whitespace
Except for line‑ending sequences, the only allowed horizontal whitespace character in source files is the ASCII space (0x20). This means:
All other whitespace characters in strings must be escaped.
Tabs are not used for indentation.
2.3.2 Escape Sequences
For characters with special escape sequences (\b, \t, \n, \f, \r, ", ', and \), use the escape sequence rather than octal (e.g., \012) or Unicode (e.g., \u000a) escapes.
2.3.3 Non‑ASCII Characters
Whether to use the actual Unicode character (e.g., ∞) or an equivalent Unicode escape (e.g., \u221e) depends on which makes the code more readable. Adding a comment explaining the character is recommended.
String unitAbbrev = "μs"; // clear without comment
String unitAbbrev = "\u03bcs"; // allowed but unnecessary
String unitAbbrev = "\u03bcs"; // hard to read
return '\ufeff' + content; // byte order markTip: Do not sacrifice readability by avoiding non‑ASCII characters out of fear that some tools cannot handle them; if a tool truly cannot handle them, fix the tool.
Source File Structure
A source file contains (in order):
License or copyright information (if required)
Package statement
Import statements
A single top‑level class (only one)
Separate each part with a blank line.
3.1 License or Copyright
If a file contains license or copyright information, it must appear at the very top.
3.2 Package Statement
The package statement must be on a single line; column limits do not apply to it.
3.3 Import Statements
3.3.1 Do Not Use Wildcards
Avoid imports such as import java.util.*;.
3.3.2 Do Not Wrap
Each import statement must be on its own line; column limits do not apply.
3.3.3 Order and Spacing
Import statements are grouped in the following order, with a blank line between groups:
All static imports (grouped together)
Imports from com.google (only if the source file is under the com.google package)
Third‑party packages, one top‑level package per group, sorted lexicographically (e.g., android, com, junit, org, sun) java imports javax imports
Within a group, do not insert blank lines and sort alphabetically.
3.4 Class Declaration
3.4.1 Only One Top‑Level Class
Each top‑level class resides in a source file named after it (with .java suffix). Exception: package‑info.java may contain no class.
3.4.2 Member Order
Member ordering should follow a logical grouping that can be explained to maintainers; do not always append new methods at the end.
3.4.2.1 Overloads: Never Separate
When a class has multiple constructors or methods with the same name, keep them together without interleaving other members.
Formatting
Terminology : A “block‑like construct” is the body of a class, method, or constructor. Array initializer blocks may be considered block‑like.
4.1 Braces
4.1.1 Use Braces Even When Optional
Braces must be used with if, else, for, do, while statements, even if the block contains a single statement (or is empty).
4.1.2 Non‑Empty Blocks: K&R Style
For non‑empty blocks, follow Kernighan & Ritchie (Egyptian brackets) style:
Opening brace on the same line as the statement
Opening brace followed by a newline
Closing brace on its own line
If the closing brace ends a statement, function, or class, follow it with a newline; otherwise, keep it on the same line (e.g., before else or a comma).
return new MyClass() { @Override public void method() { if (condition()) { try { something(); } catch (ProblemException e) { recover(); } } } };4.1.3 Empty Blocks: Compact Form
An empty block can be written as {} without a newline, except when it is part of a multi‑block statement (e.g., if/else or try/catch/finally), where the closing brace must be on a new line.
void doNothing() {}4.2 Indentation: Two Spaces
Each new block increases indentation by two spaces; when the block ends, indentation returns to the previous level. This applies to code and comments.
4.3 One Statement Per Line
Each statement must end with a newline.
4.4 Column Limit: 80 or 100
A project may choose an 80‑character or 100‑character column limit. Any line exceeding the limit must be wrapped, except for:
Lines that cannot satisfy the limit (e.g., long URLs in Javadoc). package and import statements.
Comments that may be copied to a shell command line.
4.5 Automatic Line‑Wrapping
Automatic wrapping splits long lines to stay within the column limit. There is no single deterministic rule; multiple valid wrap styles may exist. Prefer extracting a method or local variable to avoid wrapping.
4.5.1 Where to Break
Prefer breaking at higher syntactic levels:
Break before non‑assignment operators (e.g., +), leaving the operator at the start of the next line.
Break after assignment operators (e.g., =) and after the semicolon in a foreach statement.
Method or constructor name stays on the same line as the opening parenthesis.
Comma stays on the same line as 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. Consecutive wraps may increase indentation further.
4.6 Whitespace
4.6.1 Vertical Whitespace
Insert a blank line in the following situations:
Between consecutive class members (fields, constructors, methods, nested classes, static/instance initializer blocks).
Exception: a blank line between two fields is optional for logical grouping.
Between logical groups of statements inside a method body.
Optional before the first member or after the last member of a class.
To satisfy other sections’ blank‑line requirements (e.g., after import statements).
Multiple consecutive blank lines are allowed but discouraged.
4.6.2 Horizontal Whitespace
Single ASCII spaces appear in the following places (aside from language requirements and comments):
Between any keyword and the following left parenthesis (e.g., if (, for ().
Between any keyword and the preceding right brace (e.g., } else).
Before any left brace, except in annotation arguments like @SomeAnnotation({a,b}) and array initializers like String[][] x=foo;.
On both sides of binary or ternary operators, including type‑bound ampersand ( &) and catch‑block pipe ( |).
After commas, semicolons, colons, and right parentheses.
Both sides of the double‑slash comment marker ( //); multiple spaces are allowed but unnecessary.
Between a type and a variable (e.g., List list).
Inside array initializers, spaces are optional (both new int[]{1,2} and new int[]{1, 2} are acceptable).
Note: This rule does not require or forbid extra spaces at the start or end of a line; it only concerns internal spaces.
4.6.3 Horizontal Alignment: Not Required
Aligning code with variable numbers of spaces is allowed but not required. Google style does not enforce alignment.
private int x; // this is fine
private Color color; // this too
private int x; // permitted but future edits may be messy
private Color color; // may leave it unalignedTip: Alignment can improve readability but makes future edits harder and may cause unnecessary merge conflicts.
4.7 Use Parentheses to Group
Do not remove parentheses unless the author and reviewer agree that doing so will not cause misinterpretation.
4.8 Specific Constructs
4.8.1 Enum Classes
Enum constants are separated by commas; line breaks are optional. Enums without methods or Javadoc can be written in array‑initializer style:
private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }All other class formatting rules also apply to enum classes.
4.8.2 Variable Declarations
4.8.2.1 Declare One Variable Per Statement
Avoid combined declarations such as int a,b;.
4.8.2.2 Declare When Needed and Initialize Promptly
Do not declare all locals at the top of a block (a C‑style habit). Declare a variable the first time it is needed, and initialize it immediately if possible.
4.8.3 Arrays
4.8.3.1 Array Initialization as a Block‑Like Construct
Array initializers may be written as block‑like structures:
new int[] { 0, 1, 2, 3 }
new int[]{0,1,2,3}
new int[] {0, 1, 2, 3}
new int[]{0,1,2,3}4.8.3.2 Non‑C‑Style Array Declarations
The brackets belong to the type: String[] args, not String args[].
4.8.4 Switch Statements
A switch block contains one or more statement groups; each group has one or more case or default labels followed by statements.
4.8.4.1 Indentation
Switch block contents are indented by two spaces.
4.8.4.2 Fall‑Through Comments
If a case falls through to the next, add a comment (commonly // fall through) or terminate with break, continue, return, or an exception.
switch (input) {
case 1:
case 2: prepareOneOrTwo(); // fall through
case 3: handleOneTwoOrThree(); break;
default: handleLargeNumber(input);
}4.8.4.3 Default Clause Must Appear
Every switch must have a default group, even if it contains no code.
4.8.5 Annotations
Annotations appear immediately after the Javadoc block and apply to classes, methods, or constructors. Each annotation occupies its own line, except a single annotation may share the first line with the signature.
@Override
@Nullable public String getNameIfPresent() { ... }
@Override public int hashCode() { ... }
@Partial @Mock DataLoader loader;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 and may use /* ... */ or // .... For multi‑line block comments, each subsequent line starts with * aligned with the first *.
/*
* This is ...
* // And so
*/Avoid framing comments with asterisks or other decorative characters.
4.8.6.2 Comment Style Tips
Use /* ... */ for multi‑line comments when you may need to wrap them like paragraphs.
4.8.7 Modifiers
If modifiers are present, order them according to the Java Language Specification recommendation.
public protected private abstract static final transient volatile synchronized native strictfpNaming Conventions
5.1 General Rules for All Identifiers
Identifiers may contain only ASCII letters and digits and must match the regular expression \w+. Prefixes and suffixes used in other Google style guides (e.g., name_, mName, s_name, kName) are not used in Java.
5.2 Identifier‑Specific Rules
5.2.1 Package Names
Package names are all lowercase, concatenated without underscores.
5.2.2 Class Names
Class names use UpperCamelCase. They are usually nouns or noun phrases; interfaces may be adjectives. Test class names start with the class under test and end with Test (e.g., HashTest, HashIntegrationTest).
5.2.3 Method Names
Method names use lowerCamelCase and are typically verbs or verb phrases. JUnit test method names may contain underscores to separate logical components (e.g., testPop_emptyStack).
5.2.4 Constant Names
Constants use CONSTANT_CASE (all caps with underscores). A constant is a static final field that truly never changes; not every static final field qualifies.
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final Joiner COMMA_JOINER = Joiner.on(',');
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};5.2.5 Non‑Constant Fields
Non‑constant fields use lowerCamelCase and are usually nouns or noun phrases.
5.2.6 Parameter Names
Parameters use lowerCamelCase and should avoid single‑character names.
5.2.7 Local Variable Names
Local variables use lowerCamelCase. Wider abbreviations are allowed, but single‑character names should be avoided except for temporary or loop variables.
5.2.8 Type Variable Names
Type variables may be a single uppercase letter (optionally followed by a digit, e.g., E, T2) or a class‑style name ending with an uppercase T (e.g., RequestT, FooBarT).
5.3 CamelCase
Google defines a conversion process from prose to UpperCamelCase and lowerCamelCase, handling Unicode normalization, word splitting, and capitalization. Examples:
"XML HTTP request" → XmlHttpRequest (incorrect: XMLHTTPRequest)
"new customer ID" → newCustomerId (incorrect: newCustomerID)
"inner stopwatch" → innerStopwatch (incorrect: innerStopWatch)
"supports IPv6 on iOS?" → supportsIpv6OnIos (incorrect: supportsIPv6OnIOS)
"YouTube importer" → YouTubeImporter (incorrect: YoutubeImporter*)Note: Some hyphenated words have multiple acceptable forms (e.g., checkNonempty vs. checkNonEmpty ).
Programming Practices
6.1 @Override: Use When Possible
Apply the @Override annotation to any method that legitimately overrides a superclass method.
6.2 Caught Exceptions: Do Not Ignore
Generally, a caught exception should be logged or re‑thrown as an AssertionError if it is considered impossible. If truly no action is needed, add a comment explaining why.
try { int i = Integer.parseInt(response); return handleNumericResponse(i); }
catch (NumberFormatException ok) { // it's not numeric; that's fine, just continue }
return handleTextResponse(response);
// In tests, catching an expected exception may be left empty:
try { emptyStack.pop(); fail(); } catch (NoSuchElementException expected) { }6.3 Static Members: Call via Class
Invoke static members using the class name, not an instance.
Foo aFoo = ...;
Foo.aStaticMethod(); // good
aFoo.aStaticMethod(); // bad
somethingThatYieldsAFoo().aStaticMethod(); // very bad6.4 Finalizers: Disable
Avoid overriding Object.finalize(). If you must, read Effective Java Item 7 and avoid using it.
Javadoc
7.1 Formatting
7.1.1 General Form
Standard Javadoc block:
/**
* Multiple lines of Javadoc text are written here, wrapped normally...
*/
public int method(String p1) { ... }Single‑line form is allowed when the entire comment fits on one line and contains no tags.
/** An especially short bit of Javadoc. */7.1.2 Paragraphs
Blank lines separate paragraphs and appear before Javadoc tags. Except for the first paragraph, each paragraph starts with a <p> tag directly before the first word.
7.1.3 Javadoc Tags
Standard tags appear in the order: @param, @return, @throws, @deprecated. Descriptions for these tags must not be empty; if they wrap, subsequent lines must be indented at least four spaces.
7.2 Summary Sentence
Each class or member Javadoc begins with a brief summary sentence—typically a noun or verb phrase, not a full sentence. It should not start with “A {@code Foo} is …” or “This method returns …”.
7.3 Where Javadoc Is Required
At a minimum, every public class and each of its public or protected members must have Javadoc, with the following exceptions:
7.3.1 Obvious Methods
Simple, self‑explanatory methods (e.g., getFoo) may omit Javadoc.
7.3.2 Overrides
Methods that override a superclass method are not required to have Javadoc.
7.3.3 Optional Javadoc
Package‑private classes and methods should have Javadoc if they need documentation. If a comment defines the overall purpose of a class, method, or field, use Javadoc for consistency.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
