Fundamentals 27 min read

Mastering Java Code Style: Key Rules from Google’s Guide

This article presents a comprehensive overview of Google’s Java style guide, covering terminology, file naming and encoding, whitespace rules, import ordering, brace placement, indentation, line length, naming conventions, annotations, Javadoc formatting, and practical coding tips to help developers write clean, readable, and maintainable Java code.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Mastering Java Code Style: Key Rules from Google’s Guide

Source File Basics

File Name

Source files must be named exactly after their top‑level class (or enum, interface, @interface), case‑sensitive, and use the .java extension.

File Encoding

All source files are required to be UTF‑8 encoded.

Whitespace Characters

The only permitted whitespace character inside source code is the ASCII space (0x20). Tabs must not be used for indentation.

Special Escape Sequences

Characters that have a predefined escape sequence ( \b, \t, \n, \f, \r, \", \') must be written using that escape form, not octal (e.g., \012) or Unicode (e.g., \u000a) escapes.

Non‑ASCII Characters

If a non‑ASCII character improves readability, write the actual Unicode character (e.g., μ). Otherwise an equivalent Unicode escape (e.g., \u03bc) is acceptable, but a comment should explain the choice.

String unitAbbrev = "μs"; // clear without comment
String unitAbbrev = "\u03bcs"; // same meaning, less readable
return '\ufeff' + content; // byte‑order‑mark, use escape with comment

Tip: Do not avoid non‑ASCII characters out of fear that tools cannot handle them; fix the toolchain instead of sacrificing readability.

Source File Structure

A source file should contain, in order, each separated by a single blank line:

License or copyright header (if needed) package statement (single line, no column limit) import statements (no wildcards, one import per line)

Exactly one top‑level class, enum, interface, or annotation type

License or Copyright

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

Import Ordering

Imports are grouped and ordered as follows, with a blank line between groups:

Static imports

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

Third‑party packages – one top‑level package per group, sorted alphabetically (e.g., android, com, junit, org, sun) java imports javax imports

Within each group, imports are sorted alphabetically without extra blank lines.

Class Declaration

The file name must match the top‑level class name (including the .java suffix). The only exception is package-info.java, which may contain no class.

Member Order

There is no single universal rule, but members should be grouped logically and the ordering should be explainable to maintainers. New methods should not always be appended to the end; place them where they fit the logical grouping.

Overloads : When a class has multiple constructors or overloaded methods, keep those overloads together without interleaving unrelated members.

Formatting Rules

Braces

Always use braces with if, else, for, do, while, even for single statements.

Follow the Kernighan & Ritchie (Egyptian) style for non‑empty blocks: opening brace on the same line as the statement, then a newline; closing brace on its own line aligned with the start of the block.

Empty blocks may be written as {} on a single line, unless they are part of a multi‑statement construct, in which case the closing brace should be on a new line.

return new MyClass() {
  @Override public void method() {
    if (condition()) {
      try {
        something();
      } catch (ProblemException e) {
        recover();
      }
    }
  }
};

Indentation

Increase indentation by two spaces when entering a new block; decrease when exiting. The same indentation level applies to both code and comments.

One Statement per Line

Terminate each statement with a newline.

Line Length

Projects may adopt an 80‑character or 100‑character column limit. Lines that exceed the limit must be wrapped automatically, except for URLs, long Javadoc lines, package / import statements, and command‑line snippets inside comments.

Automatic Wrapping

When wrapping, prefer to break at higher‑level syntax constructs:

Break before non‑assignment operators (e.g., +) so the operator appears at the start of the next line.

Break after assignment operators (e.g., =) so the operator stays with the left‑hand side.

Subsequent wrapped lines should be indented at least four spaces relative to the first line.

Blank Lines

Use a single blank line to separate logical groups such as:

License, package, imports, and class declaration

Fields, constructors, methods, nested classes, static/instance initializer blocks within a class

Logical groups of statements inside a method

Horizontal Whitespace

Use a single space to separate keywords from following parentheses, before left braces, around binary operators, after commas, colons, semicolons, and before comments. Do not add extra spaces for visual alignment.

Note: The style guide does not require or forbid aligning symbols with variable numbers of spaces.

Parentheses for Grouping

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

Naming Conventions

Identifiers

Identifiers may contain only ASCII letters and digits and must match the regular expression \w+. Prefixes such as name_, mName, s_name, and kName are not used in Java.

Package Names

All lower‑case, concatenated without underscores.

Class Names

UpperCamelCase; typically nouns or noun phrases. Test classes start with the name of the class under test and end with Test (e.g., HashTest, HashIntegrationTest).

Method Names

lowerCamelCase; usually verbs or verb phrases. In JUnit tests, underscores may separate logical components (e.g., testPop_emptyStack).

Constant Names

Upper‑case with underscores ( CONSTANT_CASE). A constant is a static final field that truly represents an immutable value.

Non‑Constant Fields

lowerCamelCase.

Parameters

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

Local Variables

lowerCamelCase; wider abbreviations are allowed but single‑character names should be avoided unless they are loop counters.

Type Variables

Either a single capital letter optionally followed by a digit (e.g., E, T2) or a class‑style name with a trailing T (e.g., RequestT).

Programming Practices

Override Annotation

Use @Override whenever the method legitimately overrides a superclass method.

Exception Handling

Do not silently ignore caught exceptions. Either log them, re‑throw as an AssertionError, or add a comment explaining why no action is needed. In tests, catching an expected exception without a comment is acceptable.

try {
  int i = Integer.parseInt(response);
  return handleNumericResponse(i);
} catch (NumberFormatException ok) {
  // not numeric – fine, continue
}
return handleTextResponse(response);

Static Members

Access static members via the class name, not an instance.

Foo aFoo = ...;
Foo.aStaticMethod(); // good
aFoo.aStaticMethod(); // bad
somethingThatYieldsAFoo().aStaticMethod(); // very bad

Finalizers

Avoid overriding Object.finalize(). If you must, read Effective Java §7 and prefer other cleanup mechanisms.

Javadoc

General Form

Multi‑line Javadoc blocks start with /**, each line prefixed by *, and end with */. Single‑line Javadoc can be used when the comment fits on one line and contains no tags.

/**
 * Multiple lines of Javadoc text are written here,
 * wrapped normally...
 */
public int method(String p1) { ... }

Paragraphs

Separate paragraphs with a blank line. The first paragraph after /** does not need a <p> tag; subsequent paragraphs should start with <p> without a leading space.

Tag Order

When present, tags appear in the order: @param, @return, @throws, @deprecated. Descriptions for these tags must not be empty.

Summary Sentence

Every class or member Javadoc must begin with a concise summary fragment—typically a noun or verb phrase, not a full sentence. It may be capitalized and end with punctuation.

When Javadoc Is Required

At minimum, all public classes and their public or protected members need Javadoc. Exceptions include obvious methods (e.g., simple getters), overridden methods, and non‑public members when the purpose is self‑evident.

Tip: If additional context is useful for readers, include Javadoc even for seemingly obvious methods.

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.

Javabest practicesCode Formattingcoding styleProgramming ConventionsGoogle Style Guide
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

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.