Java Coding Conventions
Standard Java coding conventions — formatting, brace style, line length, and recognized style guides.
Coding conventions are the shared rules that make Java code look like it was written by one person, even when a team of fifty touches it. They cover naming, indentation, brace placement, line length, and file layout — none of which the compiler cares about, but all of which decide whether the next reader (often you, months later) can scan a method in seconds or has to decode it. Java has unusually strong conventions because they were published early, in Sun's original Code Conventions for the Java Programming Language, and they have been remarkably stable ever since.
Why conventions matter more than the compiler
The JVM runs int X=1;if(X>0){return"a";} exactly as fast as well-formatted code. Conventions exist for humans: code is read far more often than it is written, and a consistent style removes a layer of friction on every read. A second, practical payoff is diff hygiene — when everyone formats the same way, a version-control diff shows real logic changes instead of reformatting noise. Most teams enforce a single style automatically (with a formatter) precisely so that style stops being a discussion in code review.
Naming: the convention you use every line
Names carry almost all of a program's meaning, and Java's naming rules are nearly universal across the ecosystem:
| Element | Convention | Example |
|---|---|---|
| Class / interface / enum | PascalCase, noun | OrderService, HttpClient |
| Method | camelCase, verb phrase | parseDate, isEmpty |
| Field / local variable | camelCase, noun | retryCount, userName |
Constant (static final) | UPPER_SNAKE_CASE | MAX_RETRIES, DEFAULT_PORT |
| Type parameter | single capital letter | T, K, V, E |
| Package | all lowercase, dotted | com.example.billing |
public class InvoiceCalculator { // PascalCase class
private static final int MAX_ITEMS = 100; // UPPER_SNAKE_CASE constant
private int lineCount; // camelCase field
public boolean isOverLimit() { // camelCase verb, boolean reads as a question
return lineCount > MAX_ITEMS;
}
}Avoid abbreviations that are not industry-standard (accelerationTime, not accTime), and let a name's length match its scope — a loop index can be i, but a field that lives for the life of an object earns a full word.
Formatting: braces, indentation, and line length
Java overwhelmingly uses K&R brace style: the opening brace sits on the same line as the declaration, and the closing brace lines up under the start of that statement. Standard indentation is 4 spaces (never tabs in the official guides), and lines are kept to a sensible width — the classic limit was 80 columns; modern guides such as Google's use 100.
// K&R: opening brace on the same line, always use braces
if (user.isActive()) {
sendWelcome(user);
} else {
queueReminder(user);
}
// Even a one-line body gets braces — it prevents the classic "dangling statement" bug
for (Order order : orders) {
total += order.amount();
}A few rules that prevent the most common review comments: one statement per line, one blank line between methods, a space after keywords (if (, not if(), and no trailing whitespace.
Recognized style guides
You rarely invent conventions from scratch — you adopt a published guide and let a tool enforce it:
| Guide | Indent | Line width | Notes |
|---|---|---|---|
| Oracle/Sun Code Conventions | 4 spaces | 80 | The original; foundational but dated |
| Google Java Style Guide | 2 spaces | 100 | Widely adopted; backed by the google-java-format tool |
| Android (AOSP) | 4 spaces | 100 | Based on Google's, tuned for Android |
The specific guide matters less than picking one and applying it consistently. Tools such as Checkstyle (verifies style and fails the build on violations), Spotless and google-java-format (auto-format on save or commit), and IDE formatters remove the human element entirely.
A worked example: convention rules in working code
The compiler is blind to style, so a runnable program cannot "test" formatting directly. What it can do is exercise the naming and structure rules in real code — constants, camelCase methods, K&R braces, interface-typed variables — and print results that prove each piece is doing its job.
What to take from the run:
MAX_RETRIES constant = 3shows theUPPER_SNAKE_CASEconstant in use. Declaring values asprivate static finaland naming them in upper-snake-case signals "this never changes" to every reader at a glance — the convention encodes intent the compiler cannot.grossPrice(100.00) = 120.00came from a method whosecamelCaseverb name reads like an instruction. The parameternetPriceand the body's use ofTAX_RATEmake the calculation self-documenting; you understand it without a comment.grades = [A, B, C]is produced byclassify, written in K&R brace style with explicit braces on every branch — even the single-return arms. Those braces are what stop a later edit from accidentally creating a dangling statement.total name length = 10comes from an enhanced for-loop over aList<String>declared with the interface type on the left, notArrayList. Coding to the interface is the convention that keeps the rest of the code free to swap implementations.totalLength is evenshows a boolean named as a question (isEven) feeding a short, single-purpose ternary. Conventions like these are invisible when followed and jarring when broken — which is exactly why teams automate them.
What the rest of this part covers
Conventions are the surface layer; the chapters ahead move from how code looks to how it is structured:
- Clean Code — practices that keep methods small and readable beyond formatting.
- Naming Best Practices — choosing names that explain themselves.
- Immutability Best Practices — designing objects that cannot change after construction.
- SOLID Principles — the design rules that shape how classes depend on each other.