Java String contains() With Examples

Java String contains() method is used to check if the string contains specified character sequence or not.

Java String contains()

  • Java String contains() method was introduced in java 1.5 release as a utility method.
  • This method returns true if the string contains the specified sequence of char values. Else it returns false.
  • String contains() method internally uses String indexOf method, below code snippet shows the contains() method definition.
  • If the argument is null, then NullPointerException is thrown, it’s clear from the above code that there is no null check for the argument string. For example; "abc".contains(null); will throw below exception stack trace similar to below.
  • Note that string contains() method is case sensitive, so "abc".contains("A"); will return false.
  • The argument of String contains() method is java.lang.CharSequence, so any implementation classes are also fine as argument, such as StringBuffer, StringBuilder and CharBuffer.

Java String contains() method simple example

Let’s look at a simple java string contains method example.

The output of the above program statements are shown in the comments itself and self understood.

Java String contains() with case insensitive check

For case insensitive check, we can change both the strings to either upper case or lower case before calling the contents() method.

Java String contains() with CharSequence

Let’s look at examples of using String contains() method with StringBuffer, StringBuilder and CharBuffer. All these are implementations of CharSequence interface. Also note that CharBuffer is an abstract class, creating it’s instance is slightly different from other usual classes.

That’s all for java string contains method examples. If you are learning java, I would strongly recommend to go through core java tutorial.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: