Contains() Method in Salesforce Apex with Real-Time Examples

When you start writing Apex code, one thing you quickly realize is that most of your logic depends on checking values.

You need to check:

  • Does this field contain a specific word?
  • Does this list already contain this value?
  • Is this user allowed?
  • Is this industry valid?
  • Is this email a duplicate?

And in all these situations, one small but powerful method helps you: the contains() method.

In this article, we will learn about how to use the contains() method in Salesforce Apex, and along with this, I will explain:

  • Why do we use contains() in Apex
  • Where exactly is it used in real Salesforce projects
  • How it behaves with String, List, and Set
  • Real trigger example

What is contains() Method in Salesforce Apex?

The contains() method checks whether a value exists within another value. Depending on where you use it, it behaves slightly differently:

  • With String → checks if a word or text exists inside another text
  • With List → checks if a value exists inside a list
  • With Set → checks if a value exists inside a set

The method always returns a Boolean value:

  • true → if found
  • false → if not found

How contains() Work with Strings in Salesforce Apex

When you use contains() with a String, Apex scans the main String and looks for a matching sequence of characters.

If it finds that exact sequence anywhere inside the main string, it returns true. If it does not find the sequence, it returns false.

For example:

String message = 'Welcome to Salesforce Apex';
Boolean result = message.contains('Salesforce');

Here, Apex internally checks the entire sentence and tries to match the word “Salesforce”. Since that word exists inside the sentence, the result becomes true.

One important theoretical concept here is that String contains() in Apex is case-sensitive. That means:

  • “Salesforce” is different from “salesforce”
  • “Test” is different from “test”

Apex treats uppercase and lowercase letters as different characters. That is why developers often convert strings to lowercase before using contains() to make the comparison more flexible.

When used with List or Set, the method works differently. Instead of scanning characters, it checks whether the collection already holds the given element.

In the case of Set, the search is faster because Set uses a hashing mechanism internally for quick lookup.

Contains() Method in Salesforce Apex with Real-Time Examples

Below, I will explain some examples of when we use the contains method to check whether a given string is present in another string.

Example 1: Check Substring in the Apex Class

The contains(String substring) method in the Apex String class checks whether a given substring exists within the main string.

It returns a Boolean value: true if the substring is found, and false if not.

The search is case-sensitive, meaning “Hello”.contains(“he”) returns false. This method validates input or checks for specific keywords in a string.

For example, when creating a record in Salesforce, you want to validate whether an email domain is allowed; only then will the email address be accepted.

Let’s say that if the user has provided the ‘@salesforce’ domain, only email from that domain is accepted; email from other domains is not accepted.

public class StringMethods {

 public void stringMethod() {

    String email = 'user@salesforce.com';
    if(email.contains('@salesforce.com')) {
        System.debug(email + ' Allowed Domain');
    } else {
        System.debug(email + ' Not Allowd Domain');
    }
  }
}

In the code above, we use the contains() method to check whether the @salesforce.com domain is a substring of the main string; if it is, it returns true; otherwise, it returns false.

Contains() Method in Apex String Class

In the image below, you can see that we provided Gmail with the .com domain, but it displayed a “Not Allowed Domain” message.

String Class Methods in Salesforce Apex

Example 2: Check the Whitespace in the Apex Strings

Now, what if we want space between two letters in the string? For that, we have another String class method. Let’s understand how we can use it in Apex code in Salesforce.

The containsWhitespace() method in the String class checks if a string contains any whitespace characters, such as spaces, tabs, newlines, etc., and returns a Boolean value.

For example, when creating an Account record, we check that the account name is not empty and that it is entered with leading or trailing whitespace.

In the apex class below, we use the containsWhitespace() method to determine whether the account name should include whitespace. We have also used exception handling to handle the error.

public with sharing class StringMethods {

 public void checkStringMethod (Account acc) {

        if (acc.Name == null) {
            throw new CustomException (' Account Name cannot be empty.');
        }

        if (!acc.Name.containsWhitespace()) {
            throw new CustomException (' Enter Full Name and it Should contain spaces.');
        }
        try {
            upsert acc;
            System.debug (' Account saved successfully: ' + acc.Name);
        } catch (DmlException e) {
            System.debug ( 'Error while saving Account: ' + e.getMessage());
            throw e;
        }
    }
    public class CustomException extends Exception {}
}

To execute the class, we need to create an Account instance and provide the account name. First, I entered the account name correctly, which contains whitespace. Then, I executed the code, and you can see the record was saved successfully.

Contains() Method in Salesforce Apex

Now, I entered the account name without any whitespace between the two strings and then executed the code. We got an exception that we declared in the if condition, which checked the string’s whitespace, and the record was not saved.

Use Apex String Methods in Apex

Example 3: Check Keyword in Case Subject in Apex Class

Customers write different types of subjects, like:

  • Refund not received
  • Technical issue in login
  • Need help with the password
  • Refund for the wrong product

Now the company wants:

  • If the subject contains the word “Refund”, send the case to the Refund Team.
  • If the subject contains “Technical”, send it to the Technical Team.

Instead of manually checking every case, we can automate this using contains().

Why do we use contains() here? Because we are checking: Does the Subject text contain a specific word?

We are not comparing full text. We are only searching for a keyword inside a sentence. That is exactly what contains() method does.

public class Demo {   
   
    public static void containsMethod() {

       Case cs = new Case(
          Subject = 'Customer asking for Refund of product'
        );
        
        if(cs.Subject != null && cs.Subject.contains('Refund')) {
              System.debug('Assign to Refund Team');
           } else {
               System.debug('Assign to General Support');
           }
     }
}

First, we check if the Subject is not null. This prevents system errors. Then we check: contains(‘Refund’). This checks if the word “Refund” exists anywhere in the subject.

If it exists → condition becomes true. contains() helps us detect keywords inside text fields.

Check Keyword in Case Subject using Contains Method in Apex Class

Example 4: contains() Method with List in Apex

Suppose we want only certain profiles to create Opportunities. In the allowed profiles:

  • Sales User
  • Sales Manager

If any other profile tries to create an Opportunity, the system should block it.

Here we have the List of allowed profiles. Now we want to check: Does this List contain the current user’s profile?

That’s why we use List.contains().

public class Demo {   
   
    public static void containsMethod() {

        List<String> allowedProfiles = new List<String> {'Sales User','Sales Manager'};
                    
         String currentProfile = 'Sales User';
        
        if(allowedProfiles.contains(currentProfile)) {
            
            System.debug('User is allowed to create Record');
        
          } else {
              System.debug('User is NOT allowed to create Record');
          }
     }
}

Here, we created a List of allowed profile names. Then we checked whether the current profile exists inside that list.

  • If yes → allow action.
  • If not → restrict.
Use contains() Method with List in Apex

Example 5: Prevent Saving Records Using Apex

This trigger runs before insert and before update. We loop through all opportunity records.

We first check if Description is not null. Then we convert the description into lowercase to avoid case sensitivity.

Now we use two contains() checks:

  • desc.contains(‘test’)
  • desc.contains(‘dummy’)

If either of them is true, we use addError(). This will stop the record from saving and show an error message to the user.

So here, contains() helps us enforce business validation rules.

trigger OpportunityValidation on Opportunity (before insert, before update) {
    
    for (Opportunity opp : Trigger.new) {

        if (opp.Description != null) {

            if (opp.Description.toLowerCase().contains('test') || 
                opp.Description.toLowerCase().contains('dummy')) {
                opp.addError('Description contains restricted words.');
            }
        }
    }
}
Prevent Saving Records Using contains method Apex

Conclusion

I hope you have an idea of how the contains() method works in Salesforce Apex and how it can be applied in real-world business scenarios.

Whether you are checking keywords in a text field, validating allowed values using List or Set, or preventing duplicate data, contains() helps you write cleaner, more concise logic.

By understanding case sensitivity, null handling, and performance considerations, you can confidently use this method in triggers, classes, and automation projects to build strong and reliable Apex solutions.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.