Java Programming

Java Coding Standards: Naming, Structure, Javadoc and Enforceable Rules

Beginner10 min readUpdated

Coding standards exist because code is read far more often than it is written, usually by someone other than its author. This guide sets out the conventions most Java teams converge on — naming, class layout, formatting, imports, Javadoc, null handling, string and logging idioms — explains the reasoning behind each so you can apply them with judgement, and shows how to make them automatic with a formatter, Checkstyle, Error Prone and SonarQube rather than code-review nagging.

What you will learn

  • Apply the standard Java naming conventions for packages, types, methods, constants and generics
  • Lay out a class in the conventional member order with clean imports and short methods
  • Write Javadoc that documents contracts rather than restating signatures
  • Handle nulls, strings, magic numbers and logging in the idiomatic way
  • Automate style with a formatter and static analysis so reviews focus on design

Most of a codebase's lifetime is maintenance, and most maintenance is reading. A consistent style is not about aesthetics; it removes the small decisions (where does the brace go, is this a constant or a variable, what does mgr mean) so that readers spend their attention on what the code does. Java has had documented conventions since the 1990s and the industry has since converged on a fairly small set of rules, most of which a tool can check. This guide presents those rules with their reasons, targets Java 21, and ends with how to enforce them so that style never becomes a topic in code review.

Naming

Names are the most important part of a standard because they carry meaning that no formatter can add. The Java conventions are precise:

ElementConventionExamples
Packageall lower case, reverse domain, no underscorescom.example.billing.invoice
Class, interface, enum, recordUpperCamelCase, nounsInvoiceService, PaymentResult
MethodlowerCamelCase, verbs or verb phrasescalculateTotal(), isExpired(), findByEmail()
Variable, field, parameterlowerCamelCase, nounsretryCount, customerEmail
Constant (static final immutable)UPPER_SNAKE_CASEMAX_RETRIES, DEFAULT_TIMEOUT
Type parametersingle capital letterT, E, K, V, R
Enum constantUPPER_SNAKE_CASEStatus.IN_PROGRESS
Test methoddescriptive, underscores allowedrejectsNegativeAmount() or withdraw_insufficientFunds_throws()

Beyond the mechanics, good names share three properties. They are pronounceable and searchable — customerRepository can be grepped and said aloud; custRepo2 cannot be found and x matches everything. They encode the unit or type when it is ambiguous — timeoutMillis, priceCents, sizeBytes prevent the classic factor-of-1000 bug better than any comment. And they avoid noise words — InvoiceData, InvoiceInfo, InvoiceObject say nothing that Invoice does not.

Booleans read best as predicates: isActive, hasChildren, canRetry. Do not negate in the name (isNotReady) because callers end up writing !isNotReady. Acronyms follow camel case as ordinary words — HttpClient, parseXml, userId — because HTTPURLConnection is unreadable and XMLHTTPRequest is a warning from history.

A static final field is a constant only if its value is deeply immutable. static final List<String> NAMES = new ArrayList<>() is a mutable global in disguise; either make it List.of(...) or name it in lowerCamelCase to signal that it can change.

Source file and class layout

One top-level public type per file, named after it. Within the file, the conventional order keeps readers oriented:

  1. License or copyright header if the project uses one
  2. package statement
  3. Imports: static imports first, then normal imports, no wildcards, no unused imports
  4. The class Javadoc and declaration
  5. Static fields (constants first), then instance fields
  6. Constructors and static factories
  7. Methods, grouped by purpose — public API first, or in call order so a reader can follow top-down
  8. equals, hashCode, toString
  9. Nested types

Wildcard imports (import java.util.*;) hide where a type comes from and cause silent conflicts when two packages gain a class of the same name; IDEs collapse them automatically, so configure the IDE not to. Within a class, keep fields together at the top rather than scattered beside the methods that use them; a reader should be able to see the whole state of an object in one screen.

Modifier order is fixed by the language specification's recommendation and checked by every linter: public protected private abstract static final transient volatile synchronized native strictfp. Write public static final, never final static public.

Formatting

Formatting is the part of a standard that should be entirely automatic. The consensus rules:

  • Indentation: 4 spaces (Oracle) or 2 spaces (Google); never tabs, because tab width differs per editor.
  • Line length: 100 or 120 columns. The old 80-column limit predates wide screens but very long lines are still hard to scan.
  • Braces: K&R style (opening brace on the same line), and always present, even for a one-line if. The Apple goto fail bug was an unbraced if with a duplicated line.
  • One statement per line, one variable declaration per line, declared as close as possible to first use.
  • Blank lines separate logical groups: between methods, between fields and constructors, and inside a long method to mark steps — but a method that needs many such groups should be split.
  • Whitespace: after keywords (if (, for (), around binary operators, after commas; none inside parentheses.
// Consistent, tool-formatted
public Optional<Invoice> latestFor(CustomerId customerId, Clock clock) {
    Objects.requireNonNull(customerId, "customerId");
    LocalDate today = LocalDate.now(clock);

    return invoices.stream()
            .filter(invoice -> invoice.customerId().equals(customerId))
            .filter(invoice -> !invoice.issuedOn().isAfter(today))
            .max(Comparator.comparing(Invoice::issuedOn));
}

The most valuable formatting decision a team makes is to stop making formatting decisions: adopt google-java-format (or the IDE formatter with a shared, checked-in configuration through Spotless) and run it on save and in CI. A formatter that rewrites the whole file, rather than checking a subset of rules, ends every whitespace discussion permanently.

Method and class size

Small units are easier to name, test and reuse. Practical ceilings many teams enforce with Checkstyle are: methods under about 30 lines, at most 4 or 5 parameters, classes under a few hundred lines, and no more than three levels of nesting. These are smells to investigate, not laws: a switch over an enum with 20 constants is fine at 40 lines, and a parser may legitimately be 500.

Two refactorings resolve most violations. Extract method turns a commented block into a named call. Introduce parameter object turns create(String name, String email, String street, String city, String zip) into create(Person person, Address address), which also stops callers from swapping two String arguments. Deep nesting is usually fixed by guard clauses: return or throw early for the invalid cases, then write the main path unindented.

// Nested
public void ship(Order order) {
    if (order != null) {
        if (order.isPaid()) {
            if (!order.isShipped()) {
                carrier.dispatch(order);
            }
        }
    }
}

// Guard clauses
public void ship(Order order) {
    Objects.requireNonNull(order, "order");
    if (!order.isPaid()) throw new IllegalStateException("Order " + order.id() + " is not paid");
    if (order.isShipped()) return;
    carrier.dispatch(order);
}

Comments and Javadoc

Javadoc is API documentation: it describes the contract of public types and methods for people who will call them without reading the implementation. It is processed into HTML and read in IDE tooltips, so structure matters.

/**
 * Reserves stock for every line of the order.
 *
 * <p>Reservation is all-or-nothing: if any line cannot be satisfied, no stock is
 * reserved and an {@link InsufficientStockException} identifies the first failing SKU.
 * Reservations expire after {@value #RESERVATION_MINUTES} minutes unless confirmed.
 *
 * @param order the order to reserve for; must contain at least one line
 * @return a reservation token to pass to {@link #confirm(ReservationToken)}
 * @throws InsufficientStockException if any line exceeds available stock
 * @throws IllegalArgumentException if the order has no lines
 */
public ReservationToken reserve(Order order) { ... }

The first sentence is a summary that appears in indexes, so make it a complete statement of what the method does. The body explains the contract: side effects, atomicity, what happens on failure, thread-safety, units. @param, @return and @throws document every parameter, the result and every exception a caller might handle. Do not document RuntimeExceptions thrown only for programming errors unless the condition is part of the contract.

What Javadoc should not contain: a restatement of the signature ("Returns the name"), implementation details that will drift, or an author tag and change history — version control does that better. Since Java 23 the /// Markdown form is available, but on Java 21 keep to the HTML form with <p> between paragraphs.

Inside method bodies, use // comments for why: the ticket that introduced a workaround, the reason a loop is written by hand for performance, the invariant a piece of code relies on. A comment that says what a block does is a method name waiting to happen. TODO and FIXME are acceptable with an owner or ticket reference; unowned TODOs are permanent.

Language-level idioms

Several rules in most standards concern correctness rather than appearance.

Nulls. Never return null for a collection — return an empty one. Return Optional for a single value that may be absent. Validate parameters at the top of public methods with Objects.requireNonNull, and document nullable parameters (with an annotation such as @Nullable from the JSpecify or Checker Framework projects, which static analysers understand).

Strings. Compare with equals (or equalsIgnoreCase), never ==. Use String.isBlank() over trim().isEmpty(). Concatenation with + is fine on one line — since Java 9 the compiler emits an efficient invokedynamic-based concatenation — but in a loop, use StringBuilder, and for multi-line templates use text blocks (""") and formatted().

Magic numbers. Any literal other than 0, 1 and -1 deserves a named constant: if (retries > 3) becomes if (retries > MAX_RETRIES). The name documents the intent and the value has one place to change.

Equality and hashing. Override equals, hashCode and toString together, or use a record. Never base them on mutable fields for objects used as keys.

Immutability by default. final on fields, parameters used in lambdas, and local variables that are never reassigned; unmodifiable collections out of getters; records for values.

Resources. Everything AutoCloseable in a try-with-resources; never a bare close() in a finally.

Switch. Use the arrow form (case A -> ..., Java 14) so there is no fall-through; use switch expressions where the result is a value; omit default over sealed types and enums where you want the compiler to flag new constants.

Logging. Use SLF4J with parameterised messages — log.warn("Payment {} declined: {}", id, code) — never string concatenation, which pays the formatting cost even when the level is disabled. Pass the exception as the final argument so the stack trace is captured. Never log secrets or full personal data. One log line per event at the boundary, not one per layer.

Access. The narrowest scope that works: fields private, helper classes package-private, methods that subclasses need protected, and public only for the real API. Classes not designed for inheritance are final.

Tests as part of the standard

Test code follows the same conventions with two relaxations: method names may use underscores to read as a sentence, and a little duplication between tests is preferable to a helper hierarchy that hides what each test checks. Structure each test as arrange / act / assert (or given / when / then), one behaviour per test, with a name that states the behaviour: returnsEmptyWhenCustomerHasNoInvoices. Assertions use a fluent library (AssertJ) or JUnit 5's assertEquals(expected, actual) — in that argument order, so failure messages are correct. The testing subject covers the tooling in detail.

Enforcing the standard

A standard that lives in a wiki is a suggestion. Make it executable:

  1. Adopt a formatter

    Add Spotless (Gradle or Maven) configured with google-java-format or your shared Eclipse/IntelliJ formatter XML. Run spotlessApply locally and spotlessCheck in CI. Commit one formatting-only change to the whole codebase so history stays clean.
  2. Add Checkstyle for structure

    Checkstyle enforces what a formatter cannot: naming, import order, method length, parameter count, missing Javadoc on public API, modifier order, no star imports. Start from the Google or Sun configuration and remove rules you disagree with rather than adding exceptions in code.
  3. Add a bug-pattern analyser

    Error Prone (a javac plugin) and SpotBugs catch correctness problems — equals on arrays, ignored return values, format-string mismatches, missing @Override. PMD adds design rules. Treat their findings as build failures, not warnings, or they will be ignored.
  4. Track the rest in SonarQube

    A quality gate on new code — coverage, duplication, no new critical issues — keeps a legacy codebase from getting worse without demanding it be fixed all at once.
  5. Keep the IDE consistent

    Check in .editorconfig and the IDE code-style settings so that every developer's editor formats the same way as CI, and turn on save actions to organise imports and reformat.

The static-analysis guide in the testing subject goes deeper into configuring these tools. The principle is the same for all of them: rules a machine can check should be checked by a machine, so that human review is spent on naming, design and whether the code solves the right problem.

Common mistakes

Hungarian notation and type prefixes. strName, iCount, m_field describe the type, which the compiler already knows, and go stale when the type changes.

Abbreviations. calcTtlAmt saves six keystrokes once and costs every reader a decode. Spell it out.

Commented-out code. Version control remembers it; the comment only confuses.

Catch-all suppression. @SuppressWarnings("all") on a class hides real problems. Suppress one warning, on the smallest scope, with a comment saying why.

Public fields and setters for everything. Generated setters turn a class into a mutable struct. Expose behaviour, not state, as the object basics guide argues.

Boolean parameters. render(true, false) is unreadable at the call site. Use an enum or two methods.

Inconsistent spelling across a codebase. colour in one module and color in another makes searching unreliable. Pick one dialect for identifiers (American English matches the JDK) and one for prose.

Key takeaways

  • Names carry the meaning: follow the camel-case conventions exactly, encode units, avoid abbreviations and noise words, and make booleans read as predicates.
  • Lay classes out in the conventional order with explicit imports, fields at the top and short methods shaped by guard clauses.
  • Formatting is a solved problem — adopt a formatter and never discuss whitespace again.
  • Javadoc documents contracts on public API; inline comments explain why, not what.
  • Idioms that prevent bugs belong in the standard: no null collections, equals for strings, named constants, immutability by default, try-with-resources, parameterised logging.
  • Enforce with Spotless, Checkstyle, Error Prone or SpotBugs and a SonarQube quality gate, so that reviews focus on design.

Sources and further reading

Frequently asked questions

Which Java style guide should my team adopt?
Pick one that a tool can enforce and stop debating. The Google Java Style Guide with google-java-format is the most common choice because the formatter leaves nothing to argue about; Oracle's original conventions are the historical baseline most others derive from. What matters is that the whole codebase follows one style and CI rejects deviations.
How long should a method be?
Short enough to understand without scrolling and to name honestly. Many teams set a soft limit around 20 to 30 lines and a hard Checkstyle limit somewhat above it. A method that needs a comment to separate its sections is asking to be split; a method that is only called once but has a clear name is still worth extracting for readability.
Should every method have Javadoc?
No. Public API — anything another module or team calls — should document its contract: preconditions, return value, exceptions, thread-safety. Private methods and self-explanatory getters should not carry a comment that repeats the signature. A Javadoc that says 'Gets the name' on getName() is noise that trains readers to skip comments.
Are comments a sign of bad code?
Comments that explain what the code does usually are, because a better name would make them unnecessary. Comments that explain why — a workaround for a driver bug, a business rule with a ticket number, a non-obvious performance choice — are valuable and hard to replace. Write the second kind and delete the first.