Java – Check if a String contains Another String
To check if a String str1
contains another string str2
in Java, use String.contains() method. Call contains() method on the string str1
and pass the other string str2
as argument. If str1
contains the string str2
, then contains() method returns true.
Java Program
</>
Copy
public class Example {
public static void main(String[] args) {
String str1 = "apple";
String str2 = "pp";
boolean result = str1.contains(str2);
System.out.println("Does str1 contains str2? " + result);
}
}
Output
Does str1 contains str2? true
If str1
does not contain the string str2
, then contains() method returns false.
Java Program
</>
Copy
public class Example {
public static void main(String[] args) {
String str1 = "apple";
String str2 = "kk";
boolean result = str1.contains(str2);
System.out.println("Does str1 contains str2? " + result);
}
}
Output
Does str1 contains str2? false
Conclusion
In this Java Tutorial, we learned how to check if a string contains another string in Java.