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)
- Must begin with a letter,
$, or_— never a digit. - After the first character, digits are allowed.
- No spaces, and no symbols such as
-,#,@, or%. - Cannot be a reserved keyword (
class,int,return, ...). - Case-sensitive:
total,Total, andTOTALare 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)
| Thing | Style | Example |
|---|---|---|
| Variable, method | camelCase | totalPrice, sendEmail() |
| Class, interface | PascalCase | OrderService, Comparable |
| Constant | UPPER_SNAKE | MAX_RETRIES |
| Package | all lowercase | com.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
- Single letters everywhere:
x,y,tmpare fine for a two-line loop, harmful anywhere else. - Case collisions: Declaring both
countandCountcompiles but confuses every reader. - Abbreviating too hard:
usrAddrLn1saves keystrokes and costs comprehension.
Best Practices
- Name for intent, not type:
customersbeatscustomerList. - 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
- The Validator: Given
2sum,my-var,_total,double,itemCount, andMAX_SIZE, mark each valid or invalid and say why. - The Rename: Take
int d = 7; double r = 3.5; double v = d * r;and rename every identifier to describe a delivery-cost calculation. - The Convention Sweep: Write one variable, one constant, one method, and one class name that each follow the correct convention.