What is StringUtils.contains() in Java?

What is contains in Java?

contains is a static method of the StringUtils class that checks whether a given string contains the complete search string. The complete search string should be present in the given string as it is.


The comparison is case-sensitive in nature. Refer to What is StringUtils.containsIgnoreCase in java? for case-insensitive comparison.

How to import StringUtlis

StringUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

Note: For other versions of the commons-lang package, refer to the Maven Repository.

You can import the StringUtils class as follows:

import org.apache.commons.lang3.StringUtils;

Syntax


public static boolean contains(CharSequence seq, CharSequence searchSeq)

Parameters

The function takes in two parameters as described below.

  • CharSequence seq: Character sequence to search in.
  • CharSequence searchSeq: Search sequence to search for.

Return value

The function returns true if the character sequence contains a search sequence. Otherwise, it returns false.


The function will return false in case of a null parameter.

Code

In the code below, we define a sequence of characters and a search string.

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main(String[] args){
String characterSequence = "abbbcccaaaccb";
String searchString = "abc";
System.out.println(StringUtils.contains(characterSequence, searchString));
characterSequence = "atbsljkhbv";
searchString = "bsl";
System.out.println(StringUtils.contains(characterSequence, searchString));
}
}

Explanation

  1. search string = "abc"
    string = "abbbcccaaaccb"

    Although the string contains the individual characters of the search string, it doesn’t contain the complete search string as it is. Hence, the function would return false.

  2. search string = "abc"
    string = "abcdefghti"

    Since the string contains the complete search string (abc), the function would return true.

Output

The output of the code will be as follows:


false
true

true because the first sequence of characters doesn’t contain the search string and false because the second sequence of characters contains the search string.

Free Resources