Identifiers in Java
An identifier is the name given to programming elements such as:
- Classes
- Methods
- Variables
- Objects, etc.
It acts as a reference label to access the memory or logic associated with that entity.
Example:
class Addition {
void add() {
………….
………….
int num1 = scan.nextInt();
…………..
………….
}
}
In the above example:
- Addition is the class name
- add is the method name
- num1 is a variable name
All three are identifiers.
Rules for Defining Identifiers:
| # | Rule | Explanation | Example(s) |
|---|---|---|---|
| 1 | Allowed characters: [A–Z], [a–z], [0–9], _, $ | Only these characters are allowed in identifiers |
❌ class Addition@Operation {} (invalid due to @) ✅ class Addition_Operation {} ✅ class $Addition {} |
| 2 | Cannot start with a digit | Identifiers must begin with a letter, _ or $ |
✅ int temp1; ❌ int 2temp; |
| 3 | Cannot use reserved words (keywords) | Keywords are not allowed as identifiers |
❌ int if; ✅ int Void; (valid - case-sensitive) ❌ int void; ✅ int Scanner; |
| 4 | Identifiers are case-sensitive | temp and Temp are treated as different identifiers |
✅ int temp = 10; ✅ int Temp = 20; |
| 5 | No length limit, but 4–15 characters is ideal | Long names reduce readability, short names reduce clarity |
✅ int price; ✅ int countIndex; ✅ int totalSum; |
Summary:
- An identifier names a program element like a variable, method, or class.
- It must follow rules to be valid: no special symbols (except _, $), not start with a number, and not use keywords.
- Case-sensitive: MyVar ≠ myvar.
- Choose names that are descriptive and within 4–15 characters for best practice.