Java String contains() Method Examples

Java String contains() method returns true if this string contains the given character sequence.

Java String contains() method signature

String contains() method signature is:

public boolean contains(CharSequence s)

There are three classes that implements CharSequence interface.

  1. String
  2. StringBuffer
  3. StringBuilder
Java CharSequence Implementation Classes
Java CharSequence Implementation Classes

Important Points for contains() method

  • This utility method was introduced in Java 1.5
  • It uses indexOf() method to check if this string contains the argument string or not.
  • If the argument is null then NullPointerException will be thrown.
  • This method is case sensitive. For example, "x".contains("X"); will return false.
  • You can convert both the strings to lowercase for case insensitive operation. For example, "x".toLowerCase().contains("X".toLowerCase()); will return true.

String contains() Examples

  1. Let’s look at a simple example where we pass String as an argument.
  2. String s = "Hello World";
    System.out.println(s.contains("Hello")); // true
  3. We can create string objects using Unicode values. The unicode value of ‘H’ is ‘\u0048’.
  4. System.out.println(s.contains("\u0048")); // true
  5. Let’s look at an example with StringBuffer object as the argument.
  6. System.out.println(s.contains(new StringBuffer("Hello"))); // true
  7. Let’s look at an example with StringBuilder object as the argument.
  8. System.out.println(s.contains(new StringBuilder("Hello"))); // true
  9. The java.nio.CharBuffer class implements CharSequence interface. Let’s look at an example of contains() method with CharBuffer object as argument.
  10. CharBuffer cb = CharBuffer.allocate(5);
    System.out.println(cb); // Hello
    System.out.println(s.contains(cb)); // true

JShell Examples of contains() method

We can run above code snippets in JShell too.

jshell> String s = "Hello World";
s ==> "Hello World"

jshell> s.contains("Hello");
$20 ==> true

jshell> s.contains("\u0048");
$21 ==> true

jshell> s.contains(new StringBuffer("Hello"));
$22 ==> true

jshell> s.contains(new StringBuilder("Hello"));
$23 ==> true

jshell> import java.nio.CharBuffer;

jshell> CharBuffer cb = CharBuffer.allocate(5);
cb ==> 

jshell> cb.append('H');cb.append('e');cb.append('l');cb.append('l');cb.append('o');
$26 ==> 
$27 ==> 
$28 ==> 
$29 ==> 
$30 ==> 

jshell> cb.clear();
$31 ==> Hello

jshell> System.out.println(cb);

jshell> s.contains(cb)
$33 ==> true