Java Reference ยท Language Features by Version
Java code conventions
Java naming and formatting conventions: classes, methods, constants, packages, braces, indentation, imports, Javadoc and modern style for records and enums.
Java has no formatter built into the compiler, so the community relies on conventions: shared habits about how names look, where braces go and how code is organized. They do not change what a program does, but they decide how quickly another person can read it. The compiler accepts class my_class { int X; }; every Java developer will wince at it.
The conventions below follow the widely used style of the JDK itself and the major style guides (the Google Java Style Guide, the Oracle conventions, and the defaults of IntelliJ IDEA and Eclipse). Where guides disagree, such as 2 versus 4 spaces of indentation, pick one for the project and let a formatter enforce it.
package com.shop.orders; // all lowercase, reverse domain public class OrderService { // UpperCamelCase for types private static final int MAX_ITEMS = 50; // UPPER_SNAKE_CASE for constants private final List<Item> items = new ArrayList<>(); // lowerCamelCase for fields public int totalCents() { // lowerCamelCase verb for methods int sum = 0; // lowerCamelCase for locals for (Item item : items) { sum += item.priceCents(); } return sum; } }
Naming
| Element | Convention | Examples |
|---|---|---|
| Package | all lowercase, no underscores, reverse domain | com.shop.orders, org.apache.commons.io |
| Class, record, interface, enum, annotation | UpperCamelCase, nouns |
OrderService, Point, Comparable, Color |
| Method | lowerCamelCase, verbs |
findById, isEmpty, toString |
| Variable, field, parameter | lowerCamelCase, meaningful nouns |
customerName, retryCount |
Constant (static final, deeply immutable) |
UPPER_SNAKE_CASE |
MAX_RETRIES, DEFAULT_LOCALE |
| Enum constant | UPPER_SNAKE_CASE |
DAY_OF_WEEK, READ_ONLY |
| Type parameter | single capital letter, or a letter plus digit | T, E, K, V, T2 |
| Test method | descriptive lowerCamelCase |
rejectsNegativeQuantity |
More naming habits:
- Booleans read like questions:
isActive(),hasChildren(),canRetry(). Accessors aregetX(); boolean accessorsisX(); setterssetX(value). Records use plainx(). - Abbreviations count as words:
HttpClient,parseXml,userId, notHTTPClientorparseXML. The standard library is not fully consistent, but this reads best. - Avoid single letters except for loop counters (
i,j), lambda parameters in tiny lambdas (x -> x * 2), and type parameters. - Avoid prefixes and suffixes such as
m_name,IOrder,strName. UseImplonly when no better name exists. - No names that only differ by case, and never name a method like its class.
- Underscore
_alone is the unnamed variable since Java 22; using it as an identifier is an error.
Formatting
// Read-only: layout rules in one place if (items.isEmpty()) { // braces always, even for one statement return 0; } else if (items.size() == 1) { // "else" on the same line as the closing brace return items.get(0).priceCents(); } String message = "Order " + id // break before the operator when wrapping + " shipped to " + city; // continuation lines indented by +8 spaces (or +4 in Google style) switch (status) { case NEW -> start(); // arrow form: no fall-through, no break needed case DONE -> archive(); default -> throw new IllegalStateException(status.name()); }
- Indentation: 4 spaces (Oracle, IntelliJ default) or 2 (Google). Never tabs mixed with spaces.
- Line length: 100 (Google) or 120 characters is typical. Long lines wrap after commas or before operators.
- Braces: opening brace at the end of the line ("Kernighan and Ritchie" style); always use braces, which prevents the classic bug of adding a second statement under an unbraced
if. - One statement and one declaration per line.
int a, b;is legal but hides types in arrays and initializers. - Blank lines separate methods and logical blocks. No trailing whitespace, a newline at end of file.
- Spaces around binary operators and after commas, none inside parentheses, one after keywords like
ifandfor(but none after a method name).
File and member order
packagestatement (never wrapped), then a blank line.importstatements: no wildcards in application code, static imports grouped separately, no unused imports.- One top-level class per file, named like the file.
- Inside a class: static constants, instance fields, constructors, methods. Keep overloads together and put
publicAPI before helpers when practical.
Documentation
Write Javadoc (/** ... */) for public classes and methods that others call. The first sentence is a summary ending in a period; use @param, @return and @throws only when they add information. Markdown comments (///) are supported by Javadoc since Java 23. Use // comments to explain why, not what, and delete commented-out code, since version control remembers it.
/** * Returns the total price of all items, in cents. * * @return the total, never negative * @throws ArithmeticException if the sum exceeds {@code Long.MAX_VALUE} */ public long totalCents() { // Math.addExact fails loudly on overflow instead of wrapping around silently return items.stream().mapToLong(Item::priceCents).reduce(0, Math::addExact); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Tools that enforce style
- Formatters rewrite code automatically:
google-java-format, Spotless (Maven and Gradle plugin), and the formatters inside IntelliJ IDEA, Eclipse and VS Code. Run one in CI so reviews do not argue about spaces. - Linters check rules beyond layout: Checkstyle (style), PMD and SpotBugs (likely bugs), Error Prone (compiler plugin).
javac -Xlint:allalready finds many problems. - EditorConfig (
.editorconfig) shares indentation and line-ending settings between editors.
Usage notes
- Consistency beats preference. In an existing code base, follow the local style even if you would choose differently.
- Name length follows scope. A loop index is
i; a field used across a class deserves a descriptive name. - Prefer immutability and small methods, which is style at the design level:
finalfields, records for plain data, methods that fit on a screen. - Use modern syntax where it clarifies:
varwhen the type is obvious on the right-hand side, records instead of boilerplate classes, switch expressions, text blocks for multi-line strings, pattern matching instead of casts. - Use
@Overridealways, and@FunctionalInterfacefor interfaces meant for lambdas. - Public API is a promise. Name public methods carefully, since renaming them later breaks callers.