BCA / B.Tech 10 min read

Identifiers in Java

What are Identifiers in Java?

An identifier is simply a name given to an element in a program, such as a class, method, or variable. Identifiers allow you to uniquely refer to these elements in your code.

Rules for Naming Identifiers:
  • Allowed Characters: Identifiers can contain letters (A-Z, a-z), digits (0-9), underscores (_), and dollar signs ($).
  • Starting Character: They must not begin with a digit.
  • Case-Sensitivity: Java is case-sensitive, so `myVariable` and `MyVariable` are treated as two different identifiers.
  • No Keywords: An identifier cannot be a reserved Java keyword (like `class`, `public`, `int`, etc.).
  • Length: There is no official limit on the length of an identifier.

Valid vs. Invalid Identifiers:
  • Valid: userName, _my_data, $amount, User1
  • Invalid: 1user (starts with a digit), user-name (contains a hyphen), public (is a keyword)

Naming Conventions (Best Practices):

Following conventions makes code easier to read and maintain.

  • Classes and Interfaces: Use PascalCase (upper camel case), starting with an uppercase letter. E.g., public class StudentRecord { ... }
  • Variables and Methods: Use camelCase (lower camel case), starting with a lowercase letter. E.g., int studentAge;, void calculateScore() { ... }
  • Constants: Use all uppercase letters, with words separated by underscores. E.g., static final int MAX_STUDENTS = 30;
  • Packages: Use all lowercase letters. E.g., package com.example.project;