contains() method is a String class method that will check whether the string contains the specified sequence of char values. In this post, we will learn about the contains() method.
- Method declaration – public boolean contains(CharSequence s).
- What does it do? – It accepts a sequence of characters in the function’s argument and checks whether that sequence of characters is present in the string or not.
- What does it return? – It returns true or false based on whether the string contains the specified sequence of characters.
What is CharSequence? CharSequence is an interface in Java that represents a sequence of characters. This interface provides uniform, read-only access to many different kinds of char sequences. Below is the list of classes that implement this interface –
- CharBuffer
- Segment
- String
- StringBuffer
- StringBuilder
CharBuffer is an abstract class, and all others are normal classes. So, we can pass the objects of all of the normal classes into the contains() method arguments to check whether the string contains it or not.
Code Example
public class Codekru {
public static void main(String[] args) {
String str = "hello codekru";
String string = "codekru";
StringBuilder stringBuilder = new StringBuilder("codekru");
StringBuffer stringBuffer = new StringBuffer("codekru");
System.out.println("Does str contains string? " + str.contains(string));
System.out.println("Does str contains stringBuilder? " + str.contains(stringBuilder));
System.out.println("Does str contains stringBuffer? " + str.contains(stringBuffer));
}
}
Output –
Does str contains string? true
Does str contains stringBuilder? true
Does str contains stringBuffer? true
Internal implementation of the contains() method
public boolean contains(CharSequence s) {
return indexOf(s.toString()) >= 0;
}
As we can see that contains() method internally uses the indexOf() method to check whether it contains the character sequence or not.
The What If Scenarios
What if we pass an empty string into the function’s argument?
contains() method will always return true if we pass an empty string into the function’s argument.
public class Codekru {
public static void main(String[] args) {
String str1 = "hello codekru";
String str2 = "";
System.out.println(str1.contains(""));
System.out.println(str2.contains(""));
}
}
Output –
true
true
What if we pass null into the function’s argument?
It will throw NullPointerException as shown below
public class Codekru {
public static void main(String[] args) {
String str = "hello codekru";
System.out.println(str.contains(null));
}
}
Output –
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.toString()" because "s" is null
If you want to learn more about Strings and its methods, we recommend you read this article.
We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.