AlgoMaster Logo

Naming Conventions

Low Priority12 min readUpdated June 5, 2026
Listen to this chapter
Unlock Audio

Every name you pick in a Java program tells the next reader something about what it is. The compiler is happy with almost any name that follows a few mechanical rules, but the Java community has settled on a set of conventions that everyone follows: PascalCase for classes, camelCase for methods and variables, UPPER_SNAKE_CASE for constants, and lowercase dotted names for packages. This lesson covers what's enforced by the compiler, what's enforced only by convention, and why those conventions are worth following from your very first program.

What the Compiler Enforces

Before we get to convention, there are a few hard rules. An identifier in Java is any name you pick: a class, a method, a variable, a parameter, a field. The compiler enforces three rules on every identifier:

  • It must start with a letter, an underscore _, or a dollar sign $.
  • After the first character, it may contain letters, digits, underscores, and dollar signs.
  • It cannot be a Java reserved word like int, class, or return.

Identifiers are also case-sensitive. customerName and CustomerName are two different identifiers, and Java will treat them as completely unrelated names.

A small program that shows what the compiler accepts:

All four variable names compile because each starts with a legal first character. The compiler doesn't care that _backupCount and $promoCount look unusual.

Trying to start a name with a digit or use a reserved word fails immediately:

The compiler reports illegal start of expression or not a statement for the first line and <identifier> expected for the second. Both errors mean "that's not a legal name."

For reference, some of the reserved words you cannot use as identifiers:

CategoryWords
Primitivesboolean, byte, short, int, long, float, double, char
Controlif, else, for, while, do, switch, case, break, continue, return
OOPclass, interface, extends, implements, new, this, super, package, import
Modifierspublic, private, protected, static, final, abstract
Exceptionstry, catch, finally, throw, throws
Literalstrue, false, null (not technically keywords but still reserved)

You don't need to memorize the full list. Your IDE highlights reserved words in a different color, and the compiler will catch any slip-up before you can run the program.

Classes and Interfaces: PascalCase

Class and interface names use PascalCase: every word starts with a capital letter, including the first one, and there are no separators between words.

Other examples that follow the convention: Customer, Order, OrderStatus, ProductCatalog, PaymentMethod. Each word is capitalized and there are no underscores.

Interfaces follow the same rule. You'd write Comparable, Iterable, or PaymentProcessor, never comparable or payment_processor.

The reason PascalCase wins for types is readability. When you see ShoppingCart cart = new ShoppingCart();, the capital letters tell you at a glance which token is a type and which is a variable. If both were lowercase, the line would look like a soup of words and you'd have to think harder to parse it.

A common mistake is naming classes like methods:

The compiler doesn't complain. Every Java reviewer will. Stick with ShoppingCart.

Methods and Variables: camelCase

Methods and variables use camelCase: the first word is lowercase, every following word starts with a capital letter.

itemCount, unitPrice, cartTotal, and calculateTotal all follow the same shape. Compare that with how the same code looks if you fight the convention:

The compiler still accepts it. A reader scanning the file has to slow down and think "is CART_TOTAL a constant? Is UnitPrice a class?" Following the convention removes that friction.

Parameter names follow the same rule as local variables: camelCase, descriptive. pricePerItem is better than p, and quantity is better than qty unless your team has a strong reason for the abbreviation.

Constants: UPPER_SNAKE_CASE

Constants, declared as static final, use uppercase letters with underscores between words.

TAX_RATE, MAX_CART_ITEMS, and DEFAULT_CURRENCY are constants because they're declared static final: one value per class, never changes after assignment. The screaming uppercase tells the reader "this number didn't come from user input, you can rely on it not changing."

A non-constant should never use UPPER_SNAKE_CASE. Writing int CART_TOTAL = 0; inside main confuses everyone who reads it: they'll assume the value is fixed when it's a local variable.

Packages: lowercase.with.dots

Packages use all lowercase, with dots separating each segment. The convention is to start with a reverse domain name to avoid collisions.

GoodBadReason
com.shop.inventoryCom.Shop.InventoryNo uppercase in package names
com.shop.orderscom.shop.OrdersNo PascalCase in package names
io.algomaster.cartio.algoMaster.cartNo camelCase in package names
com.shop.usercom.shop.user_serviceAvoid underscores in package names

The full layout typically looks like this:

Each level of the diagram uses a different case style, and that's intentional: when you read a fully qualified name like com.shop.inventory.ProductCatalog.MAX_RESULTS, the case tells you what each segment is. The dots separate packages, the capital letter marks the class, and the all-caps tail marks a constant.

For now, the takeaway is the casing rule: lowercase, dots, no camelCase, no underscores.

Method Naming Idioms

Method names usually start with a verb because methods do things. A few idioms show up in almost every Java codebase:

  • Getters and setters. A property named email is read by getEmail() and written by setEmail(String email). For boolean properties, the getter usually starts with is, has, or can: isShipped(), hasDiscount(), canCancel(). Frameworks like Spring and Jackson rely on this pattern, so following it is more than cosmetic.
  • Boolean variables and method names. Any boolean should read like a yes-or-no question. isPaid, hasShipped, canCancel, shouldRefund. Drop the name into a sentence like "if isPaid then..." and check that it sounds natural.
  • Action methods. Methods that perform actions start with verbs: addItem, removeItem, checkout, placeOrder, applyDiscount. Avoid noun-only names like order or cart for methods. If you can rewrite the name as "do X to Y," it usually reads better.

A small Order class that puts these idioms together:

isPaid() reads naturally inside the if check: if (!paid). That's the test for whether your boolean name is good. If swapping it into a conditional sounds awkward, rename it.

Acronyms in Names

Treat acronyms as words in camelCase or PascalCase. Capitalize only the first letter, even when the acronym is two or three letters long.

GoodBad
HttpClientHTTPClient
XmlParserXMLParser
JsonReaderJSONReader
userIduserID
customerUrlcustomerURL

The reason is consistency. When you have a class name like HTTPSURLConnection, the eye can't tell where one word ends and the next begins. HttpsUrlConnection reads cleanly. The standard library mostly follows this rule (HttpURLConnection is the famous holdout that everyone points to as an example of why this matters).

For variables, the same rule applies. id, url, and xml all become regular lowercase when they appear at the start of a name (id, url, xmlBody) and capitalize only the first letter in the middle of a name (customerId, productUrl, responseXml).

Things to Avoid

A few patterns show up in early code that Java reviewers flag.

Single-letter names for anything other than loop indices or generics. Inside a loop, i, j, and k are fine for indices. Type parameters like T, E, K, and V are fine in generics. Anywhere else, a single letter hides what the variable is for. double p = 19.99 is shorter than double price = 19.99, but the savings cost you every time you read the code.

Hungarian notation. Writing strName, iCount, or bIsPaid adds the type to the name. Java already shows you the type in the declaration, so prefixing it again is noise. Use name, count, isPaid instead.

All-caps for non-constants. UPPER_SNAKE_CASE is reserved for static final constants. Using it for local variables or parameters confuses every reader, because they'll trust the value not to change.

Names that shadow built-in types or classes. Writing String String = "hello" compiles, but it shadows the type name inside that scope and makes the rest of the code hard to read. The same applies to Integer, List, Map. Pick a different name.

`$` prefix. The compiler accepts $promoCount as a name, but the dollar sign is reserved by convention for tool-generated code (inner class names like Outer$Inner use it). Don't put $ in your own identifiers.

Vague names. data, info, manager, tmp, helper, value. These names tell the reader nothing about what's stored or what the method does. A variable called data could be anything. A class called CartManager could do anything. Prefer concrete names: cartItems, customerProfile, pendingOrders.

Tests: A Note on Common Practice

Test code follows its own conventions, and knowing the casing rules upfront helps test code read the same way as production code.

  • Test classes are usually named after the class they test, with a Test suffix: ShoppingCartTest, OrderTest, CustomerRepositoryTest.
  • Test methods often use a longer, descriptive form: methodName_condition_expected. For example, applyDiscount_withExpiredCoupon_returnsOriginalPrice or checkout_emptyCart_throwsException.

The underscores in test method names are a deliberate exception to the camelCase rule, because the names get long and the underscores make them easier to scan in a failure report. This is convention, not a compiler requirement.

Bad Name vs Good Name

A side-by-side summary of common naming mistakes and the conventional fix.

CategoryBadGoodWhy
ClassshoppingcartShoppingCartClasses use PascalCase
Classshopping_cartShoppingCartNo underscores in class names
Interfacepayment_processorPaymentProcessorInterfaces use PascalCase
MethodCalculateTotalcalculateTotalMethods use camelCase
MethodtotalcalculateTotalMethods start with a verb
VariableItemCountitemCountVariables use camelCase
Variablei_countitemCountNo underscores or Hungarian prefix
VariablepproductPriceAvoid single-letter names
Booleanpaid_flagisPaidBooleans read as yes/no questions
BooleanshippedisShipped or hasShippedPrefix makes intent obvious
ConstantmaxItemsMAX_ITEMSConstants use UPPER_SNAKE_CASE
ConstantTaxRateTAX_RATEAll caps, with underscores
PackageCom.Shop.Inventorycom.shop.inventoryPackages are all lowercase
Packagecom.shop.product_catalogcom.shop.productcatalogNo underscores in package names
AcronymHTTPClientHttpClientTreat acronyms as words
AcronymuserIDuserIdOnly capitalize the first letter
Vaguedata, info, tmpcartItems, customerInfo, tempTotalNames should describe content

A Cleaned-Up Example

A small Customer example that pulls every convention together. The casing tells you what each name is without needing comments.

The package is lowercase. The class is PascalCase. The two constants are UPPER_SNAKE_CASE. The fields and methods use camelCase. The boolean is emailVerified and reads naturally inside isEmailVerified(). The getter and setter idioms match what frameworks expect. Every name is doing two jobs: describing the value and signaling its category by case.

Quiz

Naming Conventions Quiz

10 quizzes