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

  1. Must begin with a letter (A-Z or a-z), underscore (_), or dollar sign ($).
  2. Can be followed by letters, digits (0-9), underscores, or dollar signs.
  3. Cannot begin with a digit.
  4. Cannot use Java keywords as identifiers.
  5. Are case-sensitive: Variable and variable are 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.