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.