Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.contains()

Checks whether a string contains a substring.

Available since: Java 5

Syntax

public boolean contains(CharSequence s)

Parameters

ParameterTypeDescription
sCharSequenceThe substring to look for — a String or a StringBuilder.

Return value

booleantrue if the substring is found.

Examples

A simple check:

void main() {
    String text = "Java is fun";
    IO.println(text.contains("fun"));
    IO.println(text.contains("Fun"));
}

Output:

true
false

Ignoring case — convert both strings to the same case:

void main() {
    String text = "Java is FUN";
    String word = "fun";
    IO.println(text.toLowerCase().contains(word.toLowerCase()));
}

Output:

true

Notes

The method takes a string, not a char: contains('a') does not compile, write contains("a"). The empty string is contained in every string.

See also

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.