1. The Hook (The "Byte-Sized" Intro)
- In a Nutshell: Java conventions = consistent style across codebase.
- Naming: Classes = PascalCase, methods/variables = camelCase, constants = UPPER_SNAKE_CASE, packages = lowercase.dot.notation.
- File organization: package → imports → class → fields → constructors → methods → nested classes.
- Indentation: 2 or 4 spaces (never tabs!), line length ≤ 120 chars.
- Javadoc: Document public APIs, use @param, @return, @throws.
- Golden rule: Follow team conventions—consistency > personal preference!
Think of driving. Conventions = traffic rules (everyone drives on same side). Naming = road signs (consistent symbols everyone understands). Formatting = lane markings (organized flow). Javadoc = user manual (explains how things work)!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy
- Naming Conventions: Uniform system (all street numbers ascending)
- File Organization: Table of contents (predictable structure)
- Formatting: Grid paper (aligned, readable)
- Javadoc: Product label (ingredients, instructions)
3. Technical Mastery (The "Deep Dive")
java
// ===========================================
// 1. NAMING CONVENTIONS
// ===========================================
// Classes and Interfaces: PascalCase
class UserAccount { }
interface PaymentProcessor { }
abstract class AbstractShape { }
// Methods and Variables: camelCase
void calculateTotal() { }
int itemCount;
String userName;
// Constants: UPPER_SNAKE_CASE
public static final int MAX_RETRY_COUNT = 3;
public static final String DEFAULT_ENCODING = "UTF-8";
// Packages: lowercase.dot.notation
package com.company.projectname.module;
// Type Parameters: Single uppercase letter
class Box<T> { }
class Pair<K, V> { }
<T extends Comparable<T>> T findMax(List<T> list) { }
// ❌ BAD naming
class user_account { } // Class should be PascalCase
void CalculateTotal() { } // Method should be camelCase
int MAX_COUNT; // Non-final, shouldn't be UPPER_CASE
// ===========================================
// 2. FILE ORGANIZATION
// ===========================================
// ✅ GOOD: Proper order
package com.example.ecommerce; // 1. Package declaration
import java.util.List; // 2. Imports (grouped)
import java.util.ArrayList;
import com.example.common.Logger;
/**
* Represents a shopping cart.
*/
public class ShoppingCart {
// 3. Static constants
private static final int MAX_ITEMS = 100;
// 4. Instance fields
private List<Item> items;
private double total;
// 5. Constructors
public ShoppingCart() {
this.items = new ArrayList<>();
}
// 6. Public methods
public void addItem(Item item) {
items.add(item);
}
public double getTotal() {
return total;
}
// 7. Private methods
private void recalculateTotal() {
total = items.stream()
.mapToDouble(Item::getPrice)
.sum();
}
// 8. Nested classes
private static class Item {
private String name;
private double price;
}
}
// ===========================================
// 3. INDENTATION AND FORMATTING
// ===========================================
// ✅ GOOD: Consistent indentation (4 spaces)
public class Example {
public void method() {
if (condition) {
doSomething();
if (nested) {
doMore();
}
}
}
}
// ❌ BAD: Mixed tabs and spaces
public class Example {
public void method() {
if (condition) { // Tab here
doSomething(); // Spaces here
}
}
}
// Line length: 80-120 characters
// ✅ GOOD: Break long lines
String message = "This is a very long message that should be "
+ "broken into multiple lines for readability "
+ "and to stay within line length limits";
// Method chaining: One call per line
User user = new User.Builder()
.withName("Alice")
.withEmail("alice@example.com")
.withAge(30)
.build();
// ===========================================
// 4. JAVADOC DOCUMENTATION
// ===========================================
/**
* Calculates the total price of items in the cart.
*
* <p>This method applies any active discounts and taxes
* before returning the final total.</p>
*
* @param includeShipping whether to include shipping cost
* @return the total price in USD
* @throws IllegalStateException if cart is empty
* @see #applyDiscount(double)
*/
public double calculateTotal(boolean includeShipping) {
if (items.isEmpty()) {
throw new IllegalStateException("Cart is empty");
}
double total = sumItemPrices();
total = applyDiscount(total);
if (includeShipping) {
total += calculateShipping();
}
return total;
}
/**
* Represents a user in the system.
*
* <p>Users have unique IDs and email addresses.
* Use {@link UserBuilder} to create instances.</p>
*
* @since 1.0
* @author John Doe
*/
public class User {
// ...
}
// ❌ BAD: Redundant Javadoc
/**
* Gets the name.
* @return the name
*/
public String getName() {
return name;
}
// Comment adds no value!
// ✅ GOOD: Self-documenting code (no Javadoc needed)
public String getName() {
return name;
}5. The Comparison & Decision Layer
| Element | Convention | Example |
|---|---|---|
| Class | PascalCase | UserAccount |
| Method | camelCase | calculateTotal() |
| Variable | camelCase | itemCount |
| Constant | UPPER_SNAKE | MAX_SIZE |
| Package | lowercase | com.example.project |
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question: "Why are naming conventions important?" Answer:
- Readability: Instantly recognize what something is
- Maintainability: Consistent style = easier to modify
- Communication: Team understands code faster
- Tooling: IDEs/linters rely on conventions
java
// ❌ Inconsistent naming (hard to understand roles)
class user { }
class OrderPROCESSOR { }
void Do_Something() { }
// ✅ Consistent naming (clear roles)
class User { }
class OrderProcessor { }
void processOrder() { }Pro-Tips:
- Google Java Style Guide (widely adopted):
text
- Indentation: 2 spaces
- Line length: 100 characters
- Braces: K&R style (opening brace on same line)
- Imports: No wildcards (import java.util.*)- IDE Formatting (automate conventions):
text
IntelliJ IDEA: Code → Reformat Code (Ctrl+Alt+L)
Eclipse: Source → Format (Ctrl+Shift+F)
// Configure once, auto-format always!