Java Naming Conventions for Classes, Methods and Variables

Java naming conventions for packages, classes, methods, variables, constants and generics, with identifier rules, examples, a refactoring and style guides.

Cheat sheet of Java naming conventions for packages, types, methods, variables, constants, type parameters and annotations with library app examples

Java naming conventions are the agreed spelling rules for names in Java code, such as UpperCamelCase for classes, lowerCamelCase for methods and variables, UPPER_SNAKE_CASE for constants and lowercase for packages. The compiler does not enforce them, but nearly every Java library, framework and team follows them.

We follow the conventions so that a reader can tell a class from a variable or a constant by its spelling alone, and so that code from different teams and libraries reads the same way. Code reviews, IDE inspections and tools such as Checkstyle check them.

The following example names each kind of element in a small library app, and each comment shows the convention used.

public class LibraryMember {                        // class: UpperCamelCase noun
    public static final int MAX_LOANS = 5;          // constant: UPPER_SNAKE_CASE
    private String fullName;                        // field: lowerCamelCase noun
    public boolean canBorrow(int activeLoans) {     // method: lowerCamelCase verb, parameter: lowerCamelCase
        return activeLoans < MAX_LOANS;
    }
}

The case style alone tells us what each name is. We first separate the rules that javac enforces from the conventions, go through packages, types, methods, variables, constants and generics, rename a badly named method step by step, and compare the Oracle and Google style guides.

1. Identifier Rules vs Naming Conventions

Two different things decide how a name looks. The identifier rules of the JLS are part of the language, so breaking them is a compile error. The naming conventions are style, so breaking them compiles fine and only makes the code harder to read.

A legal identifier follows the rules in the list, and javac rejects everything else.

  • It contains letters, digits, _ and $, where letters include Unicode letters such as accented characters.
  • It does not start with a digit.
  • It is not a reserved keyword such as class or int, and not one of the literals true, false or null.
  • It contains no spaces, hyphens or other symbols.
  • Names are case-sensitive, so total and Total are two different variables.
int $count = 1;                 // 1, legal, but $ is meant for generated code
int _count = 2;                 // 2, legal, but against the conventions
int var = 3;                    // 3, var is a contextual keyword and still a legal variable name
int record = 4;                 // 4, the same for record
// does not compile: starts with a digit, uses a keyword, contains a hyphen
int 2ndCopy = 1;
int class = 2;
int first-name = 3;

The contextual keywords var, record, sealed, permits and yield still work as variable names, but not as class names. A declaration such as class var {} fails with ‘var’ not allowed here.

The single _ character has its own history. Since Java 9, _ alone is a keyword, and since Java 22, unnamed variables use it for a variable we must declare but never read, such as a loop variable that only counts.

List<String> titles = List.of("Dune", "Emma");
int count = 0;
for (String _ : titles) {
    count++;
}
int loops = count;              // 2

2. Naming Conventions by Element

Each kind of element has one case style, and the style matches across the JDK, Spring, Jakarta EE and almost every open source project. The conventions come from the JLS naming conventions, the Oracle code conventions and the Google Java Style Guide, which agree on all the basics.

Cheat sheet of Java naming conventions for packages, types, methods, variables, constants, type parameters and annotations with library app examples
One case style per kind of element, so the spelling of a name tells us what it is
ElementConventionExample
Package, moduleAll lowercase, reversed domaincom.howtodoinjava.library
Class, recordUpperCamelCase nounLibraryMember, BookLoan
InterfaceUpperCamelCase noun or adjectiveCatalog, Borrowable
Enum typeUpperCamelCase nounLoanStatus
Enum constantUPPER_SNAKE_CASEACTIVE, CHECKED_OUT
AnnotationUpperCamelCase@Audited
MethodlowerCamelCase verbrenewLoan(), isOverdue()
Field, local variable, parameterlowerCamelCase noundueDate, activeLoans
ConstantUPPER_SNAKE_CASEMAX_LOANS
Type parameterSingle capital letterT, E, K, V
Exception classUpperCamelCase ending in ExceptionLoanLimitExceededException
Test classClass under test plus TestLibraryMemberTest

2.1. Packages and Modules

Package names start with the reversed internet domain of the company or project, followed by the app and the layer, all in lowercase. Two companies that both write a Catalog class therefore never clash, because their full names start with different domains.

  • The name com.howtodoinjava.library.catalog follows the convention.
  • The name com.howtodoinjava.Library.Catalog compiles, but uppercase package parts look like class names.
  • For a domain with a hyphen, such as my-shop.com, the JLS suggests replacing the hyphen with _, as in com.my_shop, whereas the Google style guide joins the words, com.myshop.
  • Names that start with java are reserved for the Java SE platform.

A module takes the name of its main exported package, such as com.howtodoinjava.library, so module and package names line up.

2.2. Classes, Interfaces, Records and Enums

Type names are nouns in UpperCamelCase, because a type describes a thing, e.g. BookLoan or OverdueNotice. Interfaces are nouns as well, or adjectives ending in -able when they describe a capability, as Comparable and Runnable do in the JDK.

interface Borrowable {
    boolean isAvailable();
}
record Book(String title, int year) {}
enum LoanStatus { ACTIVE, OVERDUE, RETURNED }
@interface Audited {}

Java code does not prefix interfaces with I, as in ICatalog, a habit from C# and COM. The interface gets the plain name, Catalog, and an implementation gets a more specific one, such as DatabaseCatalog. An Impl suffix is common in Spring projects with one implementation per interface, but a descriptive name says more.

2.3. Methods

Method names are verbs or verb phrases in lowerCamelCase, because a method does something, as renewLoan() and sendReminder() do. A few prefixes have a fixed meaning that tools rely on.

  • JavaBeans getters and setters use getTitle() and setTitle(), and isAvailable() for a boolean. Frameworks such as Jackson and JPA find properties through these names.
  • Record accessors have no prefix, so the record Book has title() and year().
  • Factory methods use of(), from() or valueOf(), and conversions use toString() or toList(), as in the JDK.
  • Methods that return a boolean read as a question, such as isOverdue(), hasFines() or canBorrow().
Book book = new Book("Dune", 1965);
String title = book.title();            // "Dune"
int year = book.year();                 // 1965

2.4. Variables, Fields and Parameters

Variables use lowerCamelCase nouns that say what the value is, such as dueDate, activeLoans or memberName. The wider the scope, the more descriptive the name, so a loop index can be i while a field needs a full name.

Java code does not encode the type or the scope in the name. Hungarian prefixes such as strName and member prefixes such as mName or _name add nothing that the IDE does not already show. A boolean variable reads well with is, has or can, as in isPremium.

2.5. Constants

A constant is a static final field whose value never changes, and only constants use UPPER_SNAKE_CASE. A final instance field or a final local variable is not a constant and keeps lowerCamelCase.

class LoanRules {
    static final int MAX_LOANS = 5;                                     // constant
    static final List<String> GENRES = List.of("fiction", "poetry");    // constant, unmodifiable list
    static final List<String> waitingList = new ArrayList<>();          // not a constant, its contents change
    private final int loanDays = 14;                                    // final, but one copy per object
}
int maxLoans = LoanRules.MAX_LOANS;               // 5
int genreCount = LoanRules.GENRES.size();          // 2

The Google Java Style Guide defines a constant as a static final field whose contents are deeply immutable. A static final mutable list such as waitingList fails that test. Enum constants are constants too, so LoanStatus.OVERDUE uses the same style.

2.6. Type Parameters

Generic type parameters are single capital letters, so they never look like a class name. The JDK uses a small set consistently, which the Java generics tutorial uses as well.

  • T stands for a type, with S, U and V as the second, third and fourth types.
  • E stands for an element of a collection, as in List<E>.
  • K and V stand for the keys and values of a map.
  • R stands for a result type, as in Function<T, R>.
static <T> T firstOrDefault(List<T> items, T fallback) {
    return items.isEmpty() ? fallback : items.get(0);
}
String firstTitle = firstOrDefault(List.of("Dune", "Emma"), "none");    // "Dune"
String noTitle = firstOrDefault(List.of(), "none");                       // "none"

2.7. Acronyms in Names

Acronyms are the one place where Java code itself is inconsistent, as HttpClient and HttpURLConnection in the JDK show. Modern style guides treat an acronym as a normal word, which keeps word boundaries visible.

PreferAvoid
XmlParserXMLParser
customerIdcustomerID
HttpsUrlHTTPSURL
loadJsonConfig()loadJSONConfig()

Two-letter words such as Id and Io follow the same rule. When a project already uses the uppercase form everywhere, consistency within the project matters more than the style guide.

3. Renaming Code to Follow the Conventions

Poor names cost the most during maintenance. In a library app, a code review finds a method named calc with parameters d and f. Nobody on the team remembers that it computes late fees, that d holds days overdue per book, or that f marks a premium member.

class Calc {
    static double calc(List<Integer> d, boolean f) {
        double r = 0;
        for (int x : d) {
            r += f ? x * 0.125 : x * 0.25;
        }
        return r;
    }
}

The renamed version uses a verb phrase for the method, descriptive nouns for the parameters, a boolean that reads as a question and a named constant for the fee. The logic stays the same.

class LateFeeCalculator {
    static final double LATE_FEE_PER_DAY = 0.25;

    static double totalLateFees(List<Integer> daysOverdue, boolean isPremiumMember) {
        double feePerDay = isPremiumMember ? LATE_FEE_PER_DAY / 2 : LATE_FEE_PER_DAY;
        double total = 0;
        for (int days : daysOverdue) {
            total += days * feePerDay;
        }
        return total;
    }
}
List<Integer> overdue = List.of(4, 2);
double before = Calc.calc(overdue, true);                              // 0.75
double after = LateFeeCalculator.totalLateFees(overdue, true);         // 0.75

Both versions return the same fee, so the rename is a safe refactoring. Shift + F6 in IntelliJ IDEA and Alt + Shift + R in Eclipse rename a symbol together with every usage, which makes such renames fast.

4. Oracle vs Google Java Style Guide

Two style guides are referenced most often. The Oracle Code Conventions date from 1999 and describe the basic case styles, while the Google Java Style Guide is maintained and stricter on details. Many teams adopt Google’s rules or a variant of them.

TopicOracle Code ConventionsGoogle Java Style Guide
Case stylesUpperCamelCase types, lowerCamelCase members, uppercase constantsSame
ConstantsUppercase for class constantsOnly static final fields with deeply immutable contents
AcronymsNo ruleTreated as words, e.g. XmlHttpRequest
Package namesLowercase, reversed domainLowercase, words joined without underscores
UnderscoresOnly in constantsAlso allowed in JUnit test method names, e.g. renewLoan_whenOverdue_throws
Type parametersSingle capital letterSingle capital letter, optionally with a digit, or a class name ending in T

Tools check the rules on every build, so reviews can focus on meaning. The Checkstyle naming checks such as ConstantName, MethodName, TypeName and AbbreviationAsWordInName fail the build on a violation, and IntelliJ IDEA has matching inspections under Java, Naming conventions.

5. Java Naming Conventions FAQs

Beginners coming from Python or C# ask the most questions about these rules, mostly about underscores and prefixes.

5.1. Is camelCase mandatory in Java?

No. The compiler accepts any legal identifier, so total_fee or TotalFee as a variable compiles. CamelCase is a convention, and since every library and framework follows it, code that ignores it looks wrong to every Java reader.

5.2. Can a class name start with a lowercase letter?

Yes, it compiles, but it breaks the convention, and readers will take the name for a variable. A public class name must also match its file name, so libraryMember would need a file named libraryMember.java.

5.3. Should interface names start with I?

No, not in Java. The JDK and the major frameworks use plain names such as List and Runnable, and the implementations get the descriptive names, e.g. ArrayList.

5.4. Can we use underscores in Java variable names?

Underscores are legal, but the conventions use them only in constants such as MAX_LOANS and, in some teams, in test method names. A single _ is a keyword and declares an unnamed variable since Java 22.

5.5. How should we name boolean variables and getters?

Use a prefix that reads as a yes or no question, such as isOverdue, hasFines or canBorrow. For a boolean property, the JavaBeans getter is isOverdue(), and frameworks such as Jackson recognize it.

5.6. Why must a constant be static final?

Because final alone gives every object its own copy of the value, while static alone lets the value change. Only static final gives one value for the whole program, which is what the uppercase name indicates.

6. Conclusion

Java naming conventions give each kind of element its own case style. Types use UpperCamelCase nouns, methods use lowerCamelCase verbs, variables use lowerCamelCase nouns, constants and enum constants use UPPER_SNAKE_CASE, packages are lowercase reversed domains, and type parameters are single capital letters.

The compiler enforces only the identifier rules, such as no leading digit, no keywords and no symbols other than _ and $. The conventions are enforced by reviews, IDE inspections and Checkstyle, and following them makes the code read like the JDK and the libraries around it. The Java tutorial links the next basics, such as variables and comments.

7. References

Happy Learning !!

Source Code on Github

Leave a Comment

  1. I feel that this section:
    In Java, interfaces names, generally, should be verbs.

    Should actually be
    In Java, interfaces names, generally, should be **adjectives**.

    When people suggest things like ‘Runnable’ or ‘Tasklike’ it’s a description of the kind of object that the interface describes. ‘What kind of object is it? It is a {List|Runnable|Cancelable} type of object’

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.