Identifiers
Java Identifiers
An Identifier is a name given to different elements in a Java program so that they can be identified uniquely.
In simple words, an identifier is the name you give to things like:
- Class
- Method
- Variable
- Interface
- Package
- Label
These names help Java identify and differentiate one element from another.
🧠Let's Test Your Understanding!
How many identifiers are there in the following Java program?
public class Test {
public static void main(String[] args) {
int x = 10;
}
}
Answer: 5 Identifiers
- Test → Class name
- main → Method name
- String → Predefined class name
- args → Parameter (variable)
- x → Local variable
Rules for Java Identifiers
Before giving a name to a class, method, or variable, you should know these rules.
1. Allowed Characters
A Java identifier can contain only:
- Letters (A-Z, a-z)
- Digits (0-9)
- Dollar Sign ($)
- Underscore (_)
Using any other special character results in a compile-time error.
total$ ✔ Valid
total123 ✔ Valid
total# ✖ Invalid
total@ ✖ Invalid
2. Identifier Cannot Start with a Digit
Student1 ✔ Valid
123total ✖ Invalid
9marks ✖ Invalid
3. Java Identifiers Are Case-Sensitive
These are all different identifiers:
TOTAL
total
4. There Is No Length Limit
Java allows very long identifiers, but shorter meaningful names are recommended.
Not Recommended: studentNameWhoJoinedCollegeIn2025AndLivesInHyderabad
5. Reserved Words Cannot Be Used
int public = 20;
✖ Both are Invalid
6. Predefined Class Names Can Be Used (Avoid It)
Although Java allows it, using predefined class names makes code confusing.
System.out.println(String); 888
🧠Quick Quiz
Which of the following are valid Java identifiers?
| Identifier | Valid? |
|---|---|
| total_number | ✅ |
| total# | ❌ |
| 123total | ❌ |
| total123 | ✅ |
| ca$h | ✅ |
| _$_$_$ | ✅ |
| all@hands | ❌ |
| Java2Share | ✅ |
| Integer | ✅ |
| int | ❌ |
| Int | ✅ |
Summary
- Identifiers are names given to classes, methods, variables, interfaces, packages, and labels.
- Only letters, digits, underscore (_) and dollar sign ($) are allowed.
- An identifier cannot start with a digit.
- Java identifiers are case-sensitive.
- There is no limit on identifier length.
- Java keywords cannot be used as identifiers.
- Avoid using predefined class names like String or Integer as identifiers.
💡 Best Practice: Always choose meaningful, readable, and unique names for your identifiers. Good identifier names make your code easier to understand and maintain.
Comments
Post a Comment