Java identifiers
Identifiers are names assigned to various elements in Java programs such as variables, classes, methods, packages, and more.
What Is a Java Identifier?
An identifier gives a unique name to an element. It helps the compiler and the developer distinguish between different entities in the code.
Rules for Naming Identifiers
- Must begin with a letter (
A-Zora-z), underscore (_), or dollar sign ($). - Can be followed by letters, digits (
0-9), underscores, or dollar signs. - Cannot begin with a digit.
- Cannot use Java keywords as identifiers.
- Are case-sensitive:
Variableandvariableare different.
Valid Identifier Examples:
int age;
String studentName;
double _salary;
boolean $isLoggedIn;
Invalid Identifier Examples:
int 1number; // Starts with digit
String class; // 'class' is a keyword
float my-salary; // Hyphen not allowed
Best Practices for Identifiers
- Use camelCase for variables and methods (
totalMarks,calculateAverage). - Use PascalCase for class names (
EmployeeData,InvoiceGenerator). - Use meaningful names that reflect the purpose of the identifier.
- Avoid using
$or_unless necessary or following a specific naming convention.