Java String contains():
If you want to search a specific sequence of characters in a string, you can use contains() method in Java. In this method, we pass a char sequence as a parameter, and the method returns a boolean value(true or false). If the char sequence is found in a string, the method will return true; otherwise, it will return false.
Method signature:
The signature for a contains() method is as shown below.
boolean contains(CharSequence sequence)
Method parameters and return type:
Return type: It returns a boolean value(true or false).
Parameters: It takes a characters sequence as a parameter.
Throws: It throws NullPointerException if the sequence is null.
Example1:
In this example, we have searched for different char sequences in a string. If the char sequence is present in a string, the function will print true; otherwise, it will print false.
Source code:
public class Example1 {
public static void main(String[] args) {
String sentence1="Learn Java Programming at Online tutorials point";
System.out.println(sentence1.contains("Java Programming"));
System.out.println(sentence1.contains("Python tutorials"));
System.out.println(sentence1.contains("point"));
System.out.println(sentence1.contains("This is"));
}
}
Output:
run:
true
false
true
false
BUILD SUCCESSFUL (total time: 5 seconds)
Example 2:
You can also use the contains() method in the conditional statements to execute a specific code block. Here we have shared an example of this concept.
Source code:
public class Example2 {
public static void main(String[] args) {
String str="Data structures and algorithms are the core concepts of programming";
if(str.contains("Data structures and algorithms")){
System.out.println("Phrase found!");
} else{
System.out.println("Phrase not found");
}
}
}
Output:
run:
Phrase found!
BUILD SUCCESSFUL (total time: 0 seconds)
Example 3:
You can also use contains() method for comparing two strings just like the equal() method in Java. All you need is to pass the whole string, and the method will return a boolean value.
Source code:
public class Example3 {
public static void main(String[] args) {
String str1="Data structures and algorithms in Java";
String str2="Data structures and algorithms in Python";
if(str1.contains(str2)){
System.out.println("Strings are equal");
} else{
System.out.println("Strings are not equal");
}
}
}
Output:
run:
Strings are not equal
BUILD SUCCESSFUL (total time: 1 second)
References:
Happy Learning 🙂