L019 | Identifiers in Java | Class 9th | ICSE | Computer Applications | Java
What are Identifiers?
- Definition: Identifiers are the names given to variables, methods, classes, objects, or any other user-defined elements in a Java program.
- They allow developers to refer to memory locations, functions, or other elements programmatically.
- Identifiers must follow specific rules to ensure that they are valid and recognized by the Java compiler.
Why are Identifiers Important?
- Identifiers help in labeling different parts of a program, such as variables, methods, and classes, making the program readable and manageable.
- Without identifiers, it would be difficult to track or use memory locations and program components effectively.
Rules for Naming Identifiers
To ensure that an identifier is valid in Java, it must adhere to the following rules:
- Must start with a letter (A-Z or a-z), an underscore (
_), or a dollar sign ($).
- Example:
_value, $total, name
- Invalid:
1variable (starts with a digit)
- Can contain letters, digits (0-9), underscore (
_), and dollar sign ($).
- Example:
age25, total_Amount
- Invalid:
total-amount (contains a hyphen, which is not allowed)
- Cannot be a Java keyword or reserved word.
- Example:
int, class, for are invalid as identifiers.
- Case-sensitive: Java differentiates between uppercase and lowercase letters.
- Example:
Value and value are different identifiers.
- No spaces are allowed.
- Example:
my variable is invalid; use myVariable instead.
Types of Identifiers
Identifiers in Java are used to name the following:
- Variables: To store data values.
- Example:
int age = 25; (age is an identifier).
- Methods: To define actions or functions.
- Example:
void displayName() { } (displayName is an identifier).
- Classes: To define blueprints for objects.
- Example:
class Student { } (Student is an identifier).