Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.startsWith — checking a prefix

String.startsWith checks whether a string begins with a given prefix, optionally at a specified index.

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

Syntax

boolean startsWith(String prefix)
boolean startsWith(String prefix, int toffset)

String.startsWith returns a boolean: it checks a literal, case-sensitive prefix. It neither interprets regular expressions nor modifies the string.

text.startsWith(prefix) checks the beginning. An empty prefix or a prefix equal to the entire string produces true.

text.startsWith(prefix, toffset) checks exactly at toffset, without searching further. The zero-based index counts UTF-16 code units. An empty prefix matches at any nonnegative index up to text.length(); an index outside that range produces false.

Avoid null: a null receiver or prefix argument can cause NullPointerException.

Examples

public class Main {
    public static void main(String[] args) {
        String text = "Java SE";
        System.out.println(text.startsWith("Java"));
        System.out.println(text.startsWith("java"));
        System.out.println(text.startsWith("SE", 5));
        System.out.println(text.startsWith("", text.length()));
        System.out.println(text.startsWith("", -1));
    }
}

Result

true
false
true
true
false

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