Java String Handling

Java StringBuilder Contains Example (StringBuffer)

Java StringBuilder contains example shows how to check if StringBuilder contains specified character or String. This example also shows how to check the same in StringBuffer object.

How to check if StringBuilder contains character or String specified (StringBuffer)?

Java String class provides contains method which checks if the specified character sequence is contained within the String.

This method returns boolean depending upon whether the String contains specified sequence.

Unlike the String class, StringBuilder and StringBuffer classes do not provide contains method. However, StringBuilder/StringBuffer class provides indexOf method.

The indexOf method returns the index of the first occurrence of the specified substring. If substring is not found, it returns -1. In the below example, we are going to use indexOf method of StringBuilder class to build our own version of contains method.


As you can see from the output, the contains method returns true for first two method calls and false for the third one as StringBuilder does not contain the “Five” text. Above code also works for StringBuffer as they have similar APIs.


Please visit StringBuilder examples and StringBuffer examples to know more. Please also visit Java String Examples to learn more about String handling in Java.

Checkout ArrayList contains example, String contains example, check if array contains value or check if String contains number example to learn more.

StringBuilder JavaDoc
StringBuffer JavaDoc