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
Acronyms are written as words in camelCase and PascalCase:
Formatting
Before and after
Here is a class which compiles and works, but ignores almost every convention -
OUTPUT of the above code
And here is the same logic following the conventions - descriptive names, a record instead of anonymous
OUTPUT of the above code
Explanation of the code
(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
| Element | Convention | Examples |
| Package | all lower case, reversed domain name, no underscores | com.javabrahman.billing |
| Class, interface, enum, record | PascalCase nouns (interfaces may be adjectives) | OrderService, Comparable, PaymentStatus |
| Method | camelCase verbs or verb phrases | calculateTotal(), sendInvoice() |
| Boolean method or field | reads as a yes/no question | isEmpty(), hasStock(), canRetry |
| Getter / setter | get/set + field name (is for booleans); records use the plain name | getName(), setName(), isActive() |
| Variable, parameter, field | camelCase nouns | orderTotal, customerName |
Constant (static final) | UPPER_SNAKE_CASE | MAX_RETRIES, DEFAULT_TIMEOUT |
| Enum constant | UPPER_SNAKE_CASE | PENDING, OUT_FOR_DELIVERY |
| Type parameter | single capital letter | T, E, K, V - see genericsClick to read tutorial: Introduction to Java Generics: Why and How |
| Exception class | ends with Exception | OrderNotFoundException |
| Test class | class under test + Test | OrderServiceTest |
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:
daysUntilExpiryrather thandordays;sendWelcomeEmail()rather thanprocess(). - 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, notcustorcstmr. Common ones -id,url,max,min- are fine. - Include units when a number has one:
timeoutSeconds,priceInCents,maxFileSizeBytes. - No type prefixes: not
strName,iCountorIOrderServicefor an interface - the IDE already knows the type. - Be consistent: if one class says
fetch, do not sayget,retrieveandloadelsewhere for the same idea. - Plural for collections:
List<Order> orders, and the singular for one element -for (Order order : orders).
- 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
ifand 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.
- static constants (
public static final), then other static fields; - instance fields;
- constructors;
- methods - public ones first, with private helper methods placed after the methods that use them;
- nested classes and interfaces.
private and expose only what other code needs.
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));}}
64.76076
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));
}
}
64.76076
- Both programs print exactly the same result - style changes readability, not behaviour.
- In the first version,
Calc(L, true)says nothing about whattruemeans, andx[0]*x[1]hides which number is the price.calculateTotal(lines, true)with a parameter namedisMember, andline.amount(), explain themselves. - The unexplained
0.9became the named constantMEMBER_DISCOUNT, and the mutable, misnamedTAXbecame aprivate static finalconstant - the original'smax_itemsfield was never used and was removed. - Wildcard imports (
java.util.*) were replaced by explicit imports, which show exactly which classes are used.
- IDE formatter: IntelliJ IDEA (
Ctrl+Alt+L), Eclipse (Ctrl+Shift+F) and VS Code all reformat a file to the configured style. Share the formatter settings in the project, for example with an.editorconfigfile. See Choosing a Java IDEClick to read tutorial: Choosing a Java IDE: IntelliJ IDEA vs Eclipse vs VS Code. - Formatters: google-java-format, or Spotless in a Maven or GradleClick to read tutorial: Introduction to Maven and Gradle for Java Projects build, format the whole code base and can fail the build if code is not formatted.
- Linters: Checkstyle checks naming and layout rules; SonarLint, PMD and SpotBugs also find likely bugs.
Core Java Tutorials
Java ExecutorService and Thread Pools: An IntroductionClick to read tutorial: Java ExecutorService and Thread Pools: An Introduction Writing Javadoc Comments in Java with ExamplesClick to read tutorial: Writing Javadoc Comments in Java with Examples Debugging Java Programs in Your IDE and with jdbClick to read tutorial: Debugging Java Programs in Your IDE and with jdb Introduction to Maven and Gradle for Java ProjectsClick to read tutorial: Introduction to Maven and Gradle for Java Projects Unit Testing Basics with JUnit 5 in JavaClick to read tutorial: Unit Testing Basics with JUnit 5 in Java Stack vs Heap Memory in Java and Object ReferencesClick to read tutorial: Stack vs Heap Memory in Java and Object References
Java ExecutorService and Thread Pools: An IntroductionClick to read tutorial: Java ExecutorService and Thread Pools: An Introduction Writing Javadoc Comments in Java with ExamplesClick to read tutorial: Writing Javadoc Comments in Java with Examples Debugging Java Programs in Your IDE and with jdbClick to read tutorial: Debugging Java Programs in Your IDE and with jdb Introduction to Maven and Gradle for Java ProjectsClick to read tutorial: Introduction to Maven and Gradle for Java Projects Unit Testing Basics with JUnit 5 in JavaClick to read tutorial: Unit Testing Basics with JUnit 5 in Java Stack vs Heap Memory in Java and Object ReferencesClick to read tutorial: Stack vs Heap Memory in Java and Object References