Meaningful Names in Java: How to Name Variables, Methods and Classes
Here is a method that compiles, passes its tests and still makes every reader stop: what is getThem, what does get() return, and why 20000?
private int getThem(Car[] array) {
int a = 0;
for (Car element : array) {
if (element.get() > 20000) {
a++;
}
}
return a;
} Nothing in it is wrong for the compiler. The logic is three lines long, yet you have to execute it in your head to learn that it counts expensive cars. Rename four things and the same code explains itself:
private static final int EXPENSIVE_CAR_PRICE = 20_000;
private int countExpensiveCars(Car[] cars) {
int count = 0;
for (Car car : cars) {
if (car.cost() > EXPENSIVE_CAR_PRICE) {
count++;
}
}
return count;
} Meaningful names are identifiers that tell the reader why a variable, method or class exists, what it holds or does, and how it is meant to be used — without a comment next to it. It is the first rule of clean code because names are what we read most: code is read many times more often than it is written, and a good name pays off on every one of those readings.
Names that reveal intent
A name reveals intent when you can understand what the value means without looking at how it is calculated or reading a comment. If a variable needs a comment to explain itself, the comment is a sign that the name is not doing its job.
int d; // elapsed time in days The letter d says nothing, and the comment only helps on the line where the variable is declared. Twenty lines later the reader sees if (d > 7) and has to scroll back. Put the meaning and the unit into the name instead:
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays; The same applies to methods. getThem() from the example above hides both what it returns and which objects it looks at, while countExpensiveCars(Car[] cars) answers both questions in the signature. Notice that the literal 20000 also became a name: EXPENSIVE_CAR_PRICE tells the reader that the number is a business rule, not an accident, and gives it one place to change.
Avoid names that lie
A misleading name is worse than a vague one: a vague name makes the reader check the code, a misleading one makes them stop checking. The most common case is a type word in the name that does not match the real type.
Map<String, Account> accountList = new HashMap<>(); // not a List Someone will call accountList.get(0) expecting the first account, and on a Map<String, Account> that call compiles (the key type is Object) and quietly returns null. Call the variable accounts or accountsByNumber and the problem disappears. Leave the container type out of the name unless it really matters.
Other sources of disinformation are easy to miss:
- Names that differ in a few letters in the middle:
XYZControllerForEfficientHandlingOfStringsandXYZControllerForEfficientStorageOfStrings. Autocomplete will offer both, and the wrong one will be chosen sooner or later. - The lowercase
land the uppercaseOas variable names: in many fontsllooks like1andOlike0, soif (O == l) a = O1;reads like arithmetic with constants. - Abbreviations that mean something else in your domain:
hpcan be hit points, horsepower or Hewlett-Packard.
Make meaningful distinctions
Two names should differ only when the things they name differ, and the difference should be visible in the names. Numbered names and noise words create a distinction for the compiler but not for the reader.
// What is the difference between a1 and a2?
void copyChars(char[] a1, char[] a2) { /* ... */ }
// Now the direction of copying is obvious
void copyChars(char[] source, char[] destination) { /* ... */ } Noise words do the same thing at class level. If a project has Product, ProductInfo and ProductData, nobody can say which one to use without opening all three: Info and Data add letters, not meaning. The same goes for Customer and CustomerObject, or getAccount(), getAccountInfo() and getAccountData() in one class. Pick one word per concept and name the difference if there is one: Product and ProductPriceHistory, Customer and CustomerDto when the second one really is a transfer object.
Pronounceable and searchable names
A name should be easy to say out loud and easy to find with a text search. Code is discussed in reviews, chats and meetings, and an identifier nobody can pronounce gets spelled letter by letter or, worse, renamed differently in everyone’s head.
| Hard to read | Better | Why |
|---|---|---|
genymdhms | generationTimestamp | Can be pronounced and is understood without decoding |
modymdhms | modificationTimestamp | Pairs naturally with the previous name |
if (attempts > 7) | if (attempts > MAX_LOGIN_ATTEMPTS) | A search for 7 finds hundreds of lines; a search for the constant finds every use of the rule |
e as a field | employee | One-letter names cannot be searched at all |
cstmrAddr | customerAddress | Autocomplete makes long names free to type |
Searchability is also why constants beat literals. When the limit changes from 7 to 10, a named constant is one edit; a literal scattered across the code is a hunt, and the first missed copy becomes a bug.
How long should a name be?
The length of a name should match the size of its scope. A variable that lives for three lines can be short; a field or a public method that is used across the project needs a name that is clear without any context.
for (int i = 0; i < rows; i++) { // fine: i lives for one loop
total += prices[i];
}
private final Duration sessionIdleTimeout; // a field read from many methods One-letter names are acceptable for loop counters, lambda parameters in a one-line pipeline (s -> s.length()) and the conventional e in a catch block. Everywhere else, a long clear name is better than a short puzzling one. If a name gets awkwardly long, that is often a hint about design rather than naming: validateAndSaveCustomerAndSendEmail() is long because the method does three jobs, which is the topic of the next lesson.
Method names go the other way: the wider the use, the shorter a public method name can be, because the class gives it context. file.delete() is perfect; inside File, deleteFileFromDisk() repeats what the reader already knows.
Names in modern Java: records, var and booleans
Newer language features raise the stakes for naming because they remove the boilerplate that used to carry type information. With var and records, the name is often the only thing a reader sees.
var. Local type inference hides the type, so the variable name has to say what the value is:
var x = repository.findAll(); // a list? a stream? of what?
var activeCustomers = repository.findActive(); // the name carries the meaning Records. A record component becomes a field, a constructor parameter and an accessor at once, so one bad name appears in three places. Name components as nouns without the get prefix — the accessor of record Money(BigDecimal amount, Currency currency) is amount(), not getAmount().
Booleans. A boolean name should read as a yes/no question: isActive, hasBonus, canRetry, exists. Avoid negative names such as isNotValid or disableCache: a condition like if (!isNotValid) forces the reader to resolve a double negative. Getter naming for boolean fields (is vs get) is covered in JavaBeans naming conventions.
No prefixes for types or scope
Hungarian-style prefixes such as strName, m_count or IRepository come from languages and IDEs that could not show types. In Java the IDE shows the type and highlights fields, so the prefix only adds noise and goes stale when the type changes. Name the interface after the concept (Repository) and the implementation after what makes it different (JdbcRepository), not RepositoryImpl.
Naming conventions in one table
Meaningful names and naming conventions answer different questions: conventions say how a name is written, meaning says what it says. The Java conventions are short enough for one table; each row is explained in detail in Best Practices for Naming Java Identifiers.
| Element | Form | Examples |
|---|---|---|
| Class, record, enum | Noun, UpperCamelCase | Invoice, PrintReader, OrderStatus |
| Interface | Noun or adjective, UpperCamelCase | Comparable, Iterable, PaymentGateway |
| Method | Verb or verb phrase, lowerCamelCase | calculateTotal(), sendInvoice(), isEmpty() |
| Variable, field, parameter | Noun, lowerCamelCase | firstName, buttonHeight |
Constant (static final) | UPPER_SNAKE_CASE | MAX_WEIGHT, DEFAULT_TIMEOUT |
| Package | Lowercase, reversed domain | com.examclouds.billing |
Renaming without fear
A name is not final when the code is committed. As you learn more about the domain, a better name usually appears, and modern IDEs make the change safe: in IntelliJ IDEA, Refactor → Rename (Shift+F6) updates every reference, including usages in other files, and can rename related getters, parameters and tests at the same time.
The rename refactoring cannot see names that live outside Java code, so check those by hand: strings in reflection or JSON mapping, column names in SQL, keys in configuration files and public API names that other teams call. For a public method used outside your codebase, add the new method, mark the old one @Deprecated and let callers migrate.
A practical rule for reviews: if you had to read the body of a method to understand a call to it, propose a new name in the review comment. That one comment saves the next reader the same trip.
Frequently Asked Questions
Are single-letter variable names always bad in Java?
No. A short name is fine when its scope is tiny and the meaning is conventional: a loop index i, a lambda parameter in a one-line stream, the exception e in a catch block. The problem starts when a one-letter name lives in a field, a long method or a public signature. More in How long should a name be?
Should I put the type in a variable name, like userList or nameString?
Usually not. The type is visible in the declaration and in the IDE, and when it changes (a List becomes a Set) the name starts to lie. Use a plural noun such as users, or describe the structure by meaning, such as usersById for a map. More in Avoid names that lie.
Is it OK to use abbreviations like cnt, msg or cfg?
Widely known abbreviations such as id, url, html or max are fine. Private abbreviations like cnt, cstmr or prcssd save a few keystrokes once and cost every reader a moment of decoding. With autocomplete, the full word is free to type.
How do I name a boolean field and its getter?
Name the field as an adjective or state, such as active or bonusEligible, and the getter as a question: isActive(), isBonusEligible(); hasX() and canX() also read well. Avoid negative names like notActive, because negating them produces double negatives. The is versus get rule for getters is described in JavaBeans naming conventions.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
All module tasks →
Comments