Master Google’s Java Style Guide: Essential Formatting Rules for Clean Code
This article presents the complete Google Java Style Guide, covering terminology, file naming, encoding, whitespace, braces, line length, import ordering, class structure, naming conventions for packages, classes, methods, constants, variables, type parameters, and Javadoc formatting, providing practical coding tips for Java developers.
This document defines the complete Google Java Style Guide, specifying when a Java source file complies with the style.
Source File Basics
File Name
Source files are named after their top‑level class, case‑sensitive, with a .java extension.
File Encoding: UTF‑8
Source files must be encoded in UTF‑8.
Special Characters
Whitespace Characters Only the ASCII space character (0x20) is allowed as whitespace in source files, except for line‑terminators; tabs are not used for indentation.
Special Escape Sequences Characters with special escape sequences (\b, \t, \n, \f, \r, \" , \\' and \) must be escaped using their escape forms rather than octal or Unicode escapes.
Non‑ASCII Characters Use actual Unicode characters (e.g., ∞) or equivalent Unicode escapes (e.g., \u221e) depending on readability.
Tip: When using Unicode escapes or actual Unicode characters, add comments to explain them for better readability.
Source File Structure
A source file contains, in order, an optional license or copyright header, a package statement, import statements, and exactly one top‑level class (or package‑info.java).
License or copyright information (if any)
Package statement
Import statements
One top‑level class ( only one )
Each part is separated by a single blank line.
Class Declaration
Only One Top‑Level Class
Each top‑level class resides in a file named after the class with a .java suffix. The exception is package‑info.java, which may contain no class.
Class Member Order
Members should be ordered logically; overloads (constructors or methods with the same name) must appear together without other members in between.
Overloads: Never Separate When a class has multiple constructors or methods with the same name, they should be placed consecutively.
Formatting
Braces
Braces are required for if, else, for, do, while statements even if the block contains a single statement. Non‑empty blocks follow the Kernighan & Ritchie (Egyptian) style: the opening brace stays on the same line, the closing brace is on its own line.
return new MyClass() {
@Override public void method() {
if (condition()) {
try {
something();
} catch (ProblemException e) {
recover();
}
}
}
};Empty Blocks
An empty block may be written as {} without line breaks, unless it is part of a multi‑block statement (e.g., if/else), in which case the closing brace must be on a new line.
void doNothing() {}Indentation
Indentation uses two spaces per level for both code and comments.
One Statement per Line
Each statement ends with a line break.
Line Length
Projects may choose an 80‑character or 100‑character column limit. Lines exceeding the limit must be wrapped, except for cases where wrapping is impossible (e.g., long URLs in Javadoc) or for package and import statements.
Automatic Line Wrapping
When wrapping, prefer to break at higher‑level syntax. Break before non‑assignment operators, after assignment operators, keep method names and opening parentheses on the same line, and keep commas with the preceding token. Wrapped lines are indented at least four spaces beyond the first line.
Tip: Extracting a method or local variable can often avoid the need for wrapping.
Whitespace
Vertical Whitespace
Use a single blank line to separate consecutive class members (fields, constructors, methods, nested classes, static/instance initializer blocks). Inside method bodies, use blank lines to separate logical groups of statements.
Horizontal Whitespace
Single ASCII spaces appear between keywords and following parentheses (e.g., if (), between a closing brace and following keywords (e.g., } else), before left braces (except in annotations or array initializers), around binary operators, after commas, colons, semicolons, and before comments.
Note: This rule does not require or forbid extra spaces at the start or end of a line; it only governs internal spacing.
Naming Conventions
General Identifier Rules
Identifiers consist only of ASCII letters and digits and match the regular expression \w+. Google‑specific prefixes such as name_, mName, s_name, and kName are not used in Java.
Package Names
Package names are all lowercase, concatenated without underscores.
Class Names
Class names use UpperCamelCase and are typically nouns or noun phrases. Test classes end with Test (e.g., HashTest).
Method Names
Method names use lowerCamelCase and are usually verbs or verb phrases. JUnit test method names may contain underscores to separate logical components (e.g., testPop_emptyStack).
Constant Names
Constants use CONSTANT_CASE (all caps with underscores). A constant is a static final field that truly represents an immutable value.
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
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"};Non‑Constant Field Names
Non‑constant fields use lowerCamelCase.
Parameter Names
Parameters use lowerCamelCase and should avoid single‑character names unless they are temporary or loop variables.
Local Variable Names
Local variables use lowerCamelCase; abbreviations are allowed but should remain readable.
Type Variable Names
Type variables are either a single uppercase letter (optionally followed by a digit) or an UpperCamelCase name ending with T (e.g., RequestT).
CamelCase
UpperCamelCase is used for class names; lowerCamelCase for methods, fields, parameters, and local variables. The conversion process involves normalizing to ASCII, splitting on spaces or punctuation, lowercasing all letters, capitalizing the first letter of each word (or all but the first for lowerCamelCase), and concatenating.
"XML HTTP request" → XmlHttpRequest
"new customer ID" → newCustomerId
"inner stopwatch" → innerStopwatch
"supports IPv6 on iOS?" → supportsIpv6OnIos
"YouTube importer" → YouTubeImporterProgramming Practices
@Override
Use @Override whenever the annotation is applicable.
Caught Exceptions
Never ignore caught exceptions; either log them, re‑throw as an AssertionError, or add a comment explaining why no action is needed.
try {
int i = Integer.parseInt(response);
return handleNumericResponse(i);
} catch (NumberFormatException ok) {
// it's not numeric; that's fine, just continue
}
return handleTextResponse(response);
try {
emptyStack.pop();
fail();
} catch (NoSuchElementException expected) {
}Static Members
Invoke static members via the class name, not an instance or expression.
Foo aFoo = ...;
Foo.aStaticMethod(); // good
aFoo.aStaticMethod(); // bad
somethingThatYieldsAFoo().aStaticMethod(); // very badFinalizers
Avoid overriding Object.finalize().
Tip: If you must use a finalizer, read Effective Java Item 7 "Avoid Finalizers" first.
Javadoc
Format
Javadoc blocks start with /** and end with */. Use paragraph tags <p> for subsequent paragraphs. Standard tags appear in the order @param, @return, @throws, @deprecated.
/**
* Multiple lines of Javadoc text are written here,
* wrapped normally...
*/
public int method(String p1) { ... }
/** An especially short bit of Javadoc. */Summary Fragment
The first sentence of a Javadoc comment is a brief summary fragment, usually a noun or verb phrase, not a full sentence.
Tip: Write "Returns the customer ID." instead of "/** @return the customer ID */".
Where to Use Javadoc
At minimum, every public class and its public or protected members should have Javadoc, with exceptions for obvious getters/setters, overridden methods, and package‑private members when not needed.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
