Java Style Guide - Quick Reference
Based on Google Java Style Guide
1. File & Class Structure
File name = Class name:
javapublic class CustomerOrder { ... }Class naming:
UpperCamelCasePackage naming:
alllowercaseMember 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()
- Single space after keywords:
3. Naming Conventions
| Type | Style | Example |
|---|---|---|
| Class/Interface | UpperCamelCase | CustomerOrder |
| Method/Variable | lowerCamelCase | calculateTotal() |
| Constant | UPPER_SNAKE_CASE | MAX_SIZE |
| Package | lowercase | com.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
finalwhen possible - Avoid magic numbers → use constants
- Prefer standard library (
Collections,Streams,Optional) - Catch specific exceptions only
- Minimize
null→ preferOptional
6. Testing
- Unit tests for all public methods
- Descriptive test names:
calculateTotal_givenValidInput_returnsCorrectSum() - Use AAA pattern: Arrange → Act → Assert
7. Annotations
@Overridewhen overriding@Deprecatedwith comment@SuppressWarningsonly 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