Salesforce Apex Identifiers
What is an Identifier?
In Apex, an identifier is the name you give to things like:
• Variables
• Classes
• Methods
• Objects
It’s how Apex knows what you’re talking about when you write your code!
Think of it like this :
Imagine you’re in a toy store. Every toy has a label — like “Teddy”, “Robot”, or “LegoBox”.
These labels help you recognize which toy is which.
In Apex, identifiers work the same way — they’re names that help you refer to something you’ve created.
Why Are Identifiers Important?
Just like you have a name, every element in a program needs a name too.
That’s what identifiers are — names for your variables, classes, and methods.
Without names, you wouldn’t know how to call or use things in your program!
Rules for Writing Identifiers in Apex
Let’s keep it simple and break it down:
Rule | Explanation | Example | Invalid Example |
---|---|---|---|
Must begin with a letter (A-Z or a-z) or underscore (_) | You can’t start with a number or symbol | name, _count | 1name, $price |
Can contain letters, digits (0-9), and underscores | No spaces or special characters | user1, total_marks | user name, total-marks |
Case sensitive | Name and name are not the same | Name, name | N/A |
Cannot be a keyword | You can’t name something like class or if | ClassName, myIf | class, if |
Should be meaningful | Choose names that explain the purpose | studentAge, totalAmount | x, a1 (not clear) |
Examples in Apex
Let’s see how identifiers are used in real Apex code:
Example 1: Variable Identifier
apex
Integer studentAge = 18;
System.debug(‘Age: ‘ + studentAge);
Explanation:
Here, studentAge is an identifier. It’s a label for the value 18.
Example 2: Class Identifier
apex
public class Calculator {
public static void add() {
System.debug(‘Adding…’);
}
}
Explanation:
Calculator is a class identifier.
add is a method identifier.
Example 3: Method Identifier
apex
public class Greetings {
public static void sayHello() {
System.debug(‘Hello!’);
}
}
Explanation:
sayHello is the name (identifier) of the method that prints a message.
Example 4: Identifier Naming with Underscores and Digits
apex
String user_1_name = ‘Mubashira’;
System.debug(user_1_name);
Output:
Mubashira
Explanation:
user_1_name is a valid identifier made with letters, digits, and underscores.
Invalid Identifier Examples (and Why They Fail)
Identifier | Problem | Fix |
---|---|---|
1total | Starts with a number | total1 |
full-name | Hyphen not allowed | full_name |
if | Reserved keyword | full_name |
total marks | Space not allowed | totalMarks |