Java Naming Conventions and Code Style Guide

Introduction Code is read far more often than it is written - by teammates, by reviewers, and by you, months later. Java has well-established naming conventions and code style rules which every experienced Java developer follows, so that any Java code looks familiar. The compiler does not enforce them, but code which ignores them is immediately harder to read. This tutorial is a practical guide to Java naming conventions and code style. We will start with the naming rules for each kind of identifier, and how to choose good names. We will then cover formatting - braces, indentation, line length and blank lines - and the order of members in a class. Next we will look at small habits that make code clearer, rewrite a badly styled class, and finish with the tools that apply style automatically.

(Note - The rules for which identifiers are legal are in Java Syntax BasicsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords. This tutorial is about which names are good. It follows the common conventions of the Java community and the Google Java Style Guide.) Naming conventions
ElementConventionExamples
Packageall lower case, reversed domain name, no underscorescom.javabrahman.billing
Class, interface, enum, recordPascalCase nouns (interfaces may be adjectives)OrderService, Comparable, PaymentStatus
MethodcamelCase verbs or verb phrasescalculateTotal(), sendInvoice()
Boolean method or fieldreads as a yes/no questionisEmpty(), hasStock(), canRetry
Getter / setterget/set + field name (is for booleans); records use the plain namegetName(), setName(), isActive()
Variable, parameter, fieldcamelCase nounsorderTotal, customerName
Constant (static final)UPPER_SNAKE_CASEMAX_RETRIES, DEFAULT_TIMEOUT
Enum constantUPPER_SNAKE_CASEPENDING, OUT_FOR_DELIVERY
Type parametersingle capital letterT, E, K, V - see genericsClick to read tutorial: Introduction to Java Generics: Why and How
Exception classends with ExceptionOrderNotFoundException
Test classclass under test + TestOrderServiceTest

Acronyms are written as words in camelCase and PascalCase: HttpClient, parseXml(), customerId - not HTTPClient or customerID. (The JDK itself is not fully consistent - URL and HttpURLConnection are older names.) Choosing good names
  • Say what it is or does: daysUntilExpiry rather than d or days; sendWelcomeEmail() rather than process().
  • Length follows scope: a loop index used on two lines can be i; a field used across a class needs a full, descriptive name.
  • Avoid abbreviations that are not universal: customer, not cust or cstmr. Common ones - id, url, max, min - are fine.
  • Include units when a number has one: timeoutSeconds, priceInCents, maxFileSizeBytes.
  • No type prefixes: not strName, iCount or IOrderService for an interface - the IDE already knows the type.
  • Be consistent: if one class says fetch, do not say get, retrieve and load elsewhere for the same idea.
  • Plural for collections: List<Order> orders, and the singular for one element - for (Order order : orders).
Formatting
  • Braces: opening brace at the end of the line (the "Egyptian" or K&R style), closing brace on its own line. Always use braces, even for one-line if and loop bodies - see the missing braces bugClick to read tutorial: Java if, else if and else Statements with Examples.
  • Indentation: 2 or 4 spaces per level - pick one per project - and spaces, not tabs. Continuation lines get extra indentation (often 4 or 8).
  • Line length: 100 or 120 characters at most. Break long lines after a comma or before an operator such as ., + or &&.
  • One statement per line, and one variable declaration per line.
  • Spaces: around binary operators (a + b), after commas and keywords (if (x), for (int i = 0; ...)); none between a method name and its parenthesis (print(x)).
  • Blank lines: one between methods, and between logical groups of statements inside a long method.
Order of members in a class A consistent order lets readers find things quickly. The common order is -
  1. static constants (public static final), then other static fields;
  2. instance fields;
  3. constructors;
  4. methods - public ones first, with private helper methods placed after the methods that use them;
  5. nested classes and interfaces.
Overloaded methods and constructors should stay next to each other. Within each group, keep fields private and expose only what other code needs.
Before and after Here is a class which compiles and works, but ignores almost every convention -
A working class with poor naming and formatting
//ordercalc.java
import java.util.*;
class ordercalc{
static double TAX=0.18;public static int max_items=50;
  static double Calc(List<double[]> l,boolean b){double t=0;
   for(double[] x:l) t+=x[0]*x[1];
    if(b)t=t*0.9; return t+t*TAX;}
public static void main(String[] a){List<double[]> L=new ArrayList<>();L.add(new double[]{19.99,2});L.add(new double[]{5.25,4});
System.out.println(Calc(L,true));}}
 OUTPUT of the above code
64.76076
And here is the same logic following the conventions - descriptive names, a record instead of anonymous double[] pairs, a named constant for the discount, proper formatting and member order -
The same logic, following Java conventions
//OrderCalculator.java
import java.util.List;

public class OrderCalculator {
  private static final double TAX_RATE = 0.18;
  private static final double MEMBER_DISCOUNT = 0.10;

  record OrderLine(double unitPrice, int quantity) {
    double amount() {
      return unitPrice * quantity;
    }
  }

  static double calculateTotal(List<OrderLine> lines, boolean isMember) {
    double subtotal = 0;
    for (OrderLine line : lines) {
      subtotal += line.amount();
    }
    if (isMember) {
      subtotal = subtotal * (1 - MEMBER_DISCOUNT);
    }
    return subtotal + subtotal * TAX_RATE;
  }

  public static void main(String[] args) {
    List<OrderLine> lines = List.of(new OrderLine(19.99, 2), new OrderLine(5.25, 4));
    System.out.println(calculateTotal(lines, true));
  }
}
 OUTPUT of the above code
64.76076
Explanation of the code
  • Both programs print exactly the same result - style changes readability, not behaviour.
  • In the first version, Calc(L, true) says nothing about what true means, and x[0]*x[1] hides which number is the price. calculateTotal(lines, true) with a parameter named isMember, and line.amount(), explain themselves.
  • The unexplained 0.9 became the named constant MEMBER_DISCOUNT, and the mutable, misnamed TAX became a private static final constant - the original's max_items field was never used and was removed.
  • Wildcard imports (java.util.*) were replaced by explicit imports, which show exactly which classes are used.
Tools that apply style for you Nobody formats code by hand any more. Agree on a style once per project, and let tools apply it -
The most important rule of all is consistency: when you work in an existing code base, follow its style, even where it differs from your own preference. Summary In this tutorial we first went through the Java naming conventions - lower-case packages, PascalCase types, camelCase methods and variables, UPPER_SNAKE_CASE constants - and guidelines for choosing good names. We then covered formatting - braces, indentation, line length, spaces and blank lines - and the usual order of members in a class. Next we rewrote a working but badly styled class into one that follows the conventions, and saw that its behaviour did not change. Lastly, we looked at the IDE formatters, formatters and linters which apply style automatically. In the next tutorial, we will document code properly with Javadoc commentsClick to read tutorial: Writing Javadoc Comments in Java with Examples.