Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

Java String.contains() method

Reference for Java String.contains(): check whether a string includes a substring, case sensitivity, null handling and alternatives like matches().

String.contains() returns true if the string includes the given sequence of characters anywhere inside it. The check is literal and case-sensitive. It is a readable replacement for indexOf(x) >= 0 when you only need a yes or no answer.

The argument is a CharSequence, so you can pass a String, a StringBuilder or any other character sequence. It cannot be null.

Java
"Hello, world".contains("world");   // true
"Hello, world".contains("World");   // false

Try it

Java Searching inside strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Filtering and alternatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public boolean contains(CharSequence s)
Name Description
s The sequence of characters to look for.

Returns: true if this string contains s, otherwise false. An empty s is always contained.

Throws: NullPointerException if s is null.

Usage notes

  • Case-sensitive. Lower-case both sides (or use a regex with CASE_INSENSITIVE) for case-insensitive checks. Use a fixed locale such as Locale.ROOT if the text is not human language.
  • Literal, not regex. "a.b".contains(".") is true because it looks for a dot. For patterns, use matches() or Pattern.find().
  • Single characters: there is no contains(char). Use indexOf(c) >= 0 or contains(String.valueOf(c)).
  • Where, not just whether: use indexOf() to get a position.
  • Start or end only: use startsWith() and endsWith(), which are stricter and faster.
  • Collections have contains too, but with different meaning: list.contains(x) tests for an element equal to x, not a substring. Checking list.contains("ab") will not find "abc".
  • Performance. Implemented with indexOf, so it scans the string; O(n * m) worst case.
  • Unicode. The search is by UTF-16 code units, so it is exact for any text, including emoji and combining marks (no normalization is performed).