7.25.2014

String: contains() - Checks whether a CharSequence is present in a String

If you want to check whether a string contains a specified character sequence that implements CharSequence interface (String, StringBuffer, StringBuilder), you can use contains() method defined in java.lang.String class. This method takes a character sequence as single argument and return true if the specified argument is present in the string or false if it doesn’t.

Some critical points to be noted:
  • A CharSequence must be enclosed in double quotes (“a” and “abc” both are CharSequence).
  • If you pass empty string (“”), the method will always return true.

Exception:
If the passed argument is null, NullPointerException will be thrown.

Method Declaration:
public boolean contains(CharSequence s)

Live Example:


public class Demo {
    public static void main(String[] args) {
          String blogTitle = "Learn Java API";
          System.out.println("blogTitle: " + blogTitle);
          System.out.println("blogTitle.contains(\"Java\"): " + blogTitle.contains("Java"));
          System.out.println("blogTitle.contains(\"java\"): " + blogTitle.contains("java"));
          System.out.println("blogTitle.contains(\"j\"): " + blogTitle.contains("j"));
          System.out.println("blogTitle.contains(\"J\"): " + blogTitle.contains("J"));
          System.out.println("blogTitle.contains(\"\"): " + blogTitle.contains(""));
          System.out.println("blogTitle.contains(\"\\n\"): " + blogTitle.contains("\n"));
          try {
              System.out.println("blogTitle.contains(null): " + blogTitle.contains(null));
          } catch (NullPointerException nullPtrExp) {
              System.out.println("blogTitle.contains(null): " + "You can't pass null!!!");
          }       
    }  
}
Output: 
blogTitle: Learn Java API
blogTitle.contains("Java"): true
blogTitle.contains("java"): false
blogTitle.contains("j"): false
blogTitle.contains("J"): true
blogTitle.contains(""): true
blogTitle.contains("\n"): false
blogTitle.contains(null): You can't pass null!!!



Use the social sharing button below to spread the knowledge among others.

0 comments:

Post a Comment