Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.contains — checking for a substring

String.contains checks whether text contains a given sequence of char values. It returns boolean, is case-sensitive, and does not interpret regular expressions.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public boolean contains(CharSequence s)

String.contains returns true when the text contains the given contiguous sequence of char values; otherwise it returns false. It is case-sensitive and searches literally, without interpreting regular expressions.

The argument s has type CharSequence: it can be a String or StringBuilder, for example. The char values are UTF-16 code units, not necessarily complete Unicode characters.

The empty string "" matches every string, including an empty one. A null argument causes NullPointerException. The method reports whether a substring exists, not its position.

Examples

public class Main {
    public static void main(String[] args) {
        String text = "Java 21";
        System.out.println(text.contains("Java"));
        System.out.println(text.contains("java"));
        System.out.println(text.contains(".*"));
        System.out.println(text.contains(""));
    }
}

Result

true
false
false
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources