Skip to content

Java Style Guide - Quick Reference

Based on Google Java Style Guide


1. File & Class Structure

  • File name = Class name:

    java
    public class CustomerOrder { ... }
  • Class naming: UpperCamelCase

  • Package naming: alllowercase

  • Member order: Constants → Fields → Constructors → Methods → Inner Classes


2. Indentation & Formatting

  • Indent: 2 spaces (no tabs)
  • Max line length: 100 chars
  • Braces: Same line, always use braces
java
if (condition) {
  doSomething();
} else {
  doSomethingElse();
}
  • Whitespace:

    • Single space after keywords: if (x > 0)
    • No space between method name and parentheses: calculateTotal()

3. Naming Conventions

TypeStyleExample
Class/InterfaceUpperCamelCaseCustomerOrder
Method/VariablelowerCamelCasecalculateTotal()
ConstantUPPER_SNAKE_CASEMAX_SIZE
Packagelowercasecom.example.project

4. Comments

  • Javadoc for public APIs:
java
/**
 * Calculates total.
 * @param qty Number of items
 * @param price Price per item
 * @return Total cost
 */
public double calculateTotal(int qty, double price) { ... }
  • Inline: // short explanation
  • Block: /* multi-line explanation */

5. Best Practices

  • Use final when possible
  • Avoid magic numbers → use constants
  • Prefer standard library (Collections, Streams, Optional)
  • Catch specific exceptions only
  • Minimize null → prefer Optional

6. Testing

  • Unit tests for all public methods
  • Descriptive test names: calculateTotal_givenValidInput_returnsCorrectSum()
  • Use AAA pattern: Arrange → Act → Assert

7. Annotations

  • @Override when overriding
  • @Deprecated with comment
  • @SuppressWarnings only if necessary, document why

8. Version Control

  • Meaningful commit messages: Fix null pointer in calculateTotal
  • Small, focused commits
  • Merge after code review and passing tests

Reference

Google Java Style Guide

© 2023-2025 Maduranga Kannangara. Feel free to use or share this content. Attribution is appreciated but not required.