Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.startsWith()

Checks whether a string starts with the given prefix.

Available since: Java 1.0

Syntax

public boolean startsWith(String prefix)

Parameters

ParameterTypeDescription
prefixStringThe expected beginning of the string.

Return value

booleantrue if the string starts with prefix.

Examples

Checking the beginning of a string:

void main() {
    String url = "https://example.com";
    IO.println(url.startsWith("https://"));
    IO.println(url.startsWith("http://"));
}

Output:

true
false

Picking lines by a prefix:

void main() {
    String[] lines = {"# title", "text", "# note"};
    for (String line : lines) {
        if (line.startsWith("#")) {
            IO.println(line);
        }
    }
}

Output:

# title
# note

Notes

The check is case-sensitive. There is a version with an offset: startsWith("lo", 3) checks the text starting at index 3.

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.