Identifiers: The Art of Naming

Identifiers: The Art of Naming in Java: An identifier is any name you invent — for variables, methods, classes, and packages.

Concept Explanation

An identifier is any name you invent — for variables, methods, classes, and packages. Java keywords are fixed, but identifiers are entirely yours, and choosing them well is one of the cheapest ways to write code others can read.

Java enforces a small set of hard rules, then the community layers conventions on top.


The Hard Rules (enforced by the compiler)

  1. Must begin with a letter, $, or _ — never a digit.
  2. After the first character, digits are allowed.
  3. No spaces, and no symbols such as -, #, @, or %.
  4. Cannot be a reserved keyword (class, int, return, ...).
  5. Case-sensitive: total, Total, and TOTAL are three different identifiers.
int score = 10;        // valid
int userAge2 = 21;     // valid
int _temp = 5;         // valid, though unusual
int $rate = 3;         // valid, reserved by convention for generated code

// int 2fast = 9;      // invalid: starts with a digit
// int user-age = 30;  // invalid: hyphen is the minus operator
// int class = 1;      // invalid: reserved keyword

The Conventions (enforced by your teammates)

ThingStyleExample
Variable, methodcamelCasetotalPrice, sendEmail()
Class, interfacePascalCaseOrderService, Comparable
ConstantUPPER_SNAKEMAX_RETRIES
Packageall lowercasecom.shop.billing

Real World Example

Compare two versions of the same logic:

// Hard to maintain
int a = 40, b = 25;
double c = a * b;

// Self-documenting
int hoursWorked = 40;
int hourlyRate = 25;
double weeklyPay = hoursWorked * hourlyRate;

Both compile identically. Only one survives being read six months later.


Common Mistakes

  1. Single letters everywhere: x, y, tmp are fine for a two-line loop, harmful anywhere else.
  2. Case collisions: Declaring both count and Count compiles but confuses every reader.
  3. Abbreviating too hard: usrAddrLn1 saves keystrokes and costs comprehension.

Best Practices

  • Name for intent, not type: customers beats customerList.
  • Booleans read as questions: isActive, hasPermission.
  • Length should track scope: A loop counter can be i; a field used across a class deserves a full name.

Practice Exercises

  1. The Validator: Given 2sum, my-var, _total, double, itemCount, and MAX_SIZE, mark each valid or invalid and say why.
  2. The Rename: Take int d = 7; double r = 3.5; double v = d * r; and rename every identifier to describe a delivery-cost calculation.
  3. The Convention Sweep: Write one variable, one constant, one method, and one class name that each follow the correct convention.