String contains() Java


Existence of a substring in the main string can be checked with String contains() method.
public class Demo
{
  public static void main(String args[])
  {
    String str1 = "abcdefghi";               // string (main string)
    String str2 = "def";                     // another string (substring)
    String str3 = "ded";                     // another string (substring)

    boolean b = str1.contains(str2);         // checks whether str2 exists in str1
    System.out.println(b);                   // true

    System.out.println(str1.contains(str3)); // false as str3 does not exist in str1
   }                                         // or str1 does not contain str3
}


String contains()
Output screen on String contains() Java

Existence of a small string (substring) can be checked with indexOf() method also.

For other String and StringBuffer API methods check String and StringBuffer.

Leave a Comment

Your email address will not be published.