Writing clean Apex code is not just about using loops, collections, or SOQL efficiently. Every Salesforce developer also works with text values in almost every project. Whether you’re validating user input, creating dynamic SOQL queries, parsing API responses, or formatting email content, the Apex String Class plays an important role.
If you understand the most commonly used String methods, you can write cleaner, shorter, and more maintainable Apex code while avoiding many common mistakes.
In this guide, you’ll learn the 20 most useful Apex String methods, practical examples, best practices, performance tips, and common interview questions. By the end of this article, you’ll know which method to use in different Salesforce development scenarios.
What Is the Apex String Class?
The Apex String Class is a built-in Salesforce class that provides methods for creating, comparing, searching, modifying, formatting, and validating text values.
Almost every text-based field in Salesforce is treated as a String in Apex, including:
- Text
- Text Area
- Long Text Area
- Rich Text Area
- Phone
- URL
- Picklist values
- Record Names
Instead of writing custom logic for every text operation, developers can use predefined String methods to perform these tasks quickly.
Common use cases include:
- Validating user input
- Searching keywords
- Splitting CSV values
- Formatting messages
- Building dynamic SOQL
- Parsing API responses
- Comparing values
- Cleaning imported data
Why Every Salesforce Developer Should Learn the Apex String Class
Most Apex classes, triggers, batch jobs, integrations, and REST services work with text values.
For example, you might need to:
- Check whether an email field is empty.
- Remove unwanted spaces.
- Convert names to uppercase.
- Build dynamic queries.
- Validate phone numbers.
- Split comma-separated values.
- Replace invalid characters.
Without String methods, these tasks become unnecessarily complex.
Mastering the Apex String Class helps you:
- Write cleaner code
- Reduce development time
- Improve readability
- Avoid null pointer exceptions
- Build secure dynamic SOQL
- Create reusable utility methods
Understanding String Immutability
One important concept every developer should know is that Strings are immutable.
This means that String methods never modify the original value. Instead, they return a new String.
Example:
String company = 'Salesforce Corner';
company.toUpperCase();
System.debug(company);
Output:
Salesforce Corner
Nothing changed because the returned value wasn’t stored.
Correct approach:
String company = 'Salesforce Corner';
company = company.toUpperCase();
System.debug(company);
Output:
SALESFORCE CORNER
Understanding this behavior helps prevent unexpected bugs while working with String operations.
Method 1: String.isBlank()
Among all String methods, String.isBlank() is one of the most frequently used.
It checks whether a String is:
- Null
- Empty
- Contains only whitespace
Syntax:
String.isBlank(value);
Example:
String firstName = '';
if(String.isBlank(firstName)){
System.debug('Name is required');
}
Output:
Name is required
When Should You Use It?
Use String.isBlank() whenever you’re validating user input before processing records.
Example scenarios:
- Before inserting records
- Before updating records
- Validating Flow inputs
- Checking API payloads
- Screen Flow validations
Instead of writing:
if(name == null || name.trim() == ''){
Use:
if(String.isBlank(name)){
The second approach is shorter, cleaner, and much easier to maintain.
Method 2: String.isNotBlank()
This method performs the opposite operation.
It returns true only when the String contains actual text.
Example:
String email = '[email protected]';
if(String.isNotBlank(email)){
System.debug('Email is available');
}
Output:
Email is available
This method is commonly used before:
- Sending emails
- Calling APIs
- Building dynamic SOQL
- Displaying messages
- Updating records
Method 3: contains()
The contains() method checks whether one String contains another String.
Syntax:
string.contains(value);
Example:
String company = 'Salesforce Corner';
Boolean result = company.contains('Corner');
System.debug(result);
Output:
true
Real-world use cases include:
- Keyword search
- Email validation
- URL checking
- Product matching
- Search filters
Method 4: containsIgnoreCase()
Unlike contains(), this method ignores uppercase and lowercase differences.
Example:
String company = 'Salesforce Corner';
Boolean result = company.containsIgnoreCase('corner');
System.debug(result);
Output:
true
This is useful when comparing values entered by different users because user input may not follow consistent capitalization.
Method 5: startsWith()
The startsWith() method checks whether a String begins with a specific value.
Example:
String recordName = 'ACC-1001';
System.debug(
recordName.startsWith('ACC')
);
Output:
true
Common use cases:
- Record numbering
- Invoice numbers
- Custom IDs
- Product codes
- Prefix validation
Method 6: endsWith()
This method checks whether a String ends with specific text.
Example:
String fileName = 'resume.pdf';
System.debug(
fileName.endsWith('.pdf')
);
Output:
true
Developers often use this method while validating uploaded file formats.
Method 7: equals()
The equals() method compares two Strings and returns true only if both values are exactly the same.
Unlike some other methods, equals() is case-sensitive.
Example:
String role1 = 'Admin';
String role2 = 'Admin';
System.debug(role1.equals(role2));
Output:
true
Now change the second value:
String role1 = 'Admin';
String role2 = 'admin';
System.debug(role1.equals(role2));
Output:
false
When Should You Use It?
Use equals() when you want an exact match, such as:
- Comparing Record Types
- Checking API values
- Validating picklist values
- Comparing custom settings
Method 8: equalsIgnoreCase()
Sometimes users enter values with different capitalization.
Instead of converting everything to lowercase, simply use equalsIgnoreCase().
Example:
String status = 'Closed Won';
if(status.equalsIgnoreCase('closed won')){
System.debug('Opportunity Closed');
}
Output:
Opportunity Closed
This method is commonly used while validating user input from:
- Screen Flows
- LWC
- REST APIs
- Web Forms
Method 9: substring()
The substring() method extracts a portion of a String.
Syntax:
string.substring(startIndex);
or
string.substring(startIndex,endIndex);
Example:
String company = 'Salesforce Corner';
System.debug(
company.substring(11)
);
Output:
Corner
Another example:
System.debug(
company.substring(0,10)
);
Output:
Salesforce
Real Project Example
Suppose an external system sends Order IDs like:
ORD-2026-4589
Extract only the order number:
String order = 'ORD-2026-4589';
String orderNo =
order.substring(9);
System.debug(orderNo);
Output:
4589
Method 10: split()
The split() method divides a String into multiple values.
Example:
String skills =
'Apex,LWC,Flow,SOQL';
List<String> skillList =
skills.split(',');
System.debug(skillList);
Output:
(Apex, LWC, Flow, SOQL)
Real Salesforce Example
Suppose a custom setting stores multiple email addresses:
[email protected],[email protected],[email protected]
Using split(), you can easily convert them into a List before sending notifications.
Developers also use this method while parsing CSV files and API responses.
Method 11: String.join()
The opposite of split() is String.join().
It combines multiple values into one String.
Example:
List<String> cities =
new List<String>{
'Delhi',
'Mumbai',
'Jaipur'
};
String result =
String.join(cities,', ');
System.debug(result);
Output:
Delhi, Mumbai, Jaipur
Why Use String.join()?
Many developers concatenate Strings inside loops.
Bad approach:
String names = '';
for(Account acc : accounts){
names += acc.Name + ',';
}
Better approach:
List<String> accountNames =
new List<String>();
for(Account acc : accounts){
accountNames.add(acc.Name);
}
String names =
String.join(accountNames,', ');
This produces cleaner code and performs better when processing large collections.
Method 12: replace()
The replace() method replaces one value with another.
Example:
String phone =
'999-888-777';
phone =
phone.replace('-',' ');
System.debug(phone);
Output:
999 888 777
Real Use Case
This method is useful while:
- Cleaning imported data
- Formatting phone numbers
- Removing unwanted characters
- Updating text before storing records
Method 13: replaceAll()
Unlike replace(), replaceAll() supports regular expressions.
Example:
String value =
'2026-07-15';
System.debug(
value.replaceAll('-','/')
);
Output:
2026/07/15
Developers often use replaceAll() while validating imported files or cleaning API payloads.
Method 14: trim()
Sometimes users accidentally save leading or trailing spaces.
Example:
String company =
' Salesforce Corner ';
company =
company.trim();
System.debug(company);
Output:
Salesforce Corner
Always trim user input before validation because invisible spaces often cause duplicate records and comparison failures.
Common Mistakes While Working with Strings
Even experienced developers make mistakes when working with Strings.
Some of the most common ones include:
- Using
== ''instead ofString.isBlank() - Forgetting that Strings are immutable
- Concatenating Strings inside loops
- Ignoring null values before comparison
- Building dynamic SOQL without escaping user input
Avoiding these mistakes improves both code quality and application performance.
Method 15: toUpperCase()
The toUpperCase() method converts every character in a String to uppercase.
Example:
String company = 'Salesforce Corner';
System.debug(company.toUpperCase());
Output:
SALESFORCE CORNER
When Should You Use It?
This method is useful when:
- Standardizing imported data
- Comparing values regardless of capitalization
- Creating formatted reports
- Exporting data
Instead of storing different variations like:
- salesforce
- Salesforce
- SALESFORCE
You can convert them into one consistent format.
Method 16: toLowerCase()
This method converts every character to lowercase.
Example:
String email = '[email protected]';
System.debug(email.toLowerCase());
Output
[email protected]
Developers often convert emails, usernames, and API values to lowercase before comparison.
Method 17: capitalize()
The capitalize() method converts only the first character into uppercase.
Example:
String city = 'jaipur';
System.debug(city.capitalize());
Output
Jaipur
This is helpful when displaying customer names, cities, or account names in a cleaner format.
Method 18: String.valueOf()
Sometimes you need to convert another data type into a String.
Instead of manually concatenating values, use String.valueOf().
Example:
Integer totalRecords = 250;
String total =
String.valueOf(totalRecords);
System.debug(total);
Output
250
It also works with:
- Integer
- Decimal
- Date
- DateTime
- Boolean
- Id
- SObject
Real-world example:
Account acc =
new Account(Name='Salesforce Corner');
System.debug(
String.valueOf(acc.Id)
);
Method 19: String.format()
Instead of joining multiple Strings manually, use String.format().
Example:
String message =
String.format(
'Hello {0}, welcome to {1}',
new List<Object>{
'Rahul',
'Salesforce Corner'
}
);
System.debug(message);
Output
Hello Rahul, welcome to Salesforce Corner
Real Salesforce Example
Suppose you’re sending an email notification.
Instead of writing:
'Hello ' + userName +
', your Case ' +
caseNumber +
' has been closed.'
Use:
String.format(
'Hello {0}, your Case {1} has been closed.',
new List<Object>{
userName,
caseNumber
}
);
The code becomes much easier to read and maintain.
Method 20: escapeSingleQuotes()
This is one of the most important methods from a security perspective.
Whenever user input is used in Dynamic SOQL, always escape single quotes.
Unsafe code:
String query =
'SELECT Id FROM Account WHERE Name = \''
+ userInput +
'\'';
Safe version:
String safeName =
String.escapeSingleQuotes(userInput);
String query =
'SELECT Id FROM Account WHERE Name = \''
+ safeName +
'\'';
Using escapeSingleQuotes() helps prevent SOQL Injection attacks.
Although bind variables should be your first choice, this method is extremely useful when building Dynamic SOQL.
Performance Tips for Working with Strings
Small improvements can make your Apex code easier to maintain and more efficient.
Follow these recommendations whenever you work with Strings:
- Use String.isBlank() instead of multiple null checks.
- Avoid String concatenation inside loops.
- Use String.join() for large collections.
- Trim user input before saving records.
- Prefer equalsIgnoreCase() when user capitalization may vary.
- Use escapeSingleQuotes() with Dynamic SOQL.
- Store reusable messages as Custom Labels whenever possible.
Real Project Examples
The Apex String Class appears in almost every Salesforce project.
Common scenarios include:
| Scenario | Method Used |
|---|---|
| Validate email | isBlank() |
| Search keywords | contains() |
| Read CSV files | split() |
| Generate CSV | join() |
| Build email messages | format() |
| Dynamic SOQL | escapeSingleQuotes() |
| Remove spaces | trim() |
| Convert IDs | valueOf() |
Once you become familiar with these methods, you’ll find yourself using them in triggers, Batch Apex, Queueable Apex, REST APIs, Lightning Web Components, and integrations
Frequently Asked Questions
Which Apex String method is used most often?
Most developers frequently use:
- String.isBlank()
- contains()
- split()
- trim()
- valueOf()
- escapeSingleQuotes()
Are Strings mutable in Apex?
No.
Strings are immutable, which means every String method returns a new value instead of modifying the existing one.
Which method prevents SOQL Injection?
Use String.escapeSingleQuotes() whenever you’re working with Dynamic SOQL.
Which method should I use instead of checking == ''?
Always use String.isBlank() because it handles null values, empty Strings, and whitespace together.
Can String methods be used in Triggers?
Yes.
String methods are commonly used in Apex Triggers, Batch Apex, Queueable Apex, Future Methods, Schedulable Apex, and REST services.
Final Thoughts
Working with text values is a daily part of Salesforce development, and knowing the right String methods can significantly improve the quality of your Apex code. Instead of writing lengthy custom logic, the built-in methods provided by the Apex String Class allow you to validate input, manipulate text, build dynamic queries, and format output with much less code.
The methods covered in this guide are the ones you’ll use most often in real Salesforce projects. Whether you’re writing triggers, Batch Apex, integrations, or Lightning components, mastering these methods will help you write cleaner, safer, and more maintainable applications.
As you continue building Apex solutions, focus on choosing the right String method for each scenario rather than creating custom implementations. Doing so not only saves development time but also makes your code easier for other developers to understand and maintain.
Related Articles
- How to Prevent Recursive Triggers in Salesforce Apex
- How to Fix Too Many SOQL Queries: 101 Error in Salesforce
- Apex Switch Statements vs If-Else: When and How to Use Each
- Apex Trigger in Salesforce: Complete Beginner Guide with Examples
- Salesforce Governor Limits with Real Examples and Best Practices