Java 25 (LTS) reference · String Methods

Java String startsWith() Method

Return true if the string begins with a prefix. endsWith() checks the end the same way.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.startsWith(prefix)

Parameters

ParameterDescription
prefix
String
The text to check for.

Return value

true or false.

Examples

Prefixes and suffixes
public class Main {
    public static void main(String[] args) {
        String path = "/admin/users";
        System.out.println(path.startsWith("/admin"));
        System.out.println(path.endsWith(".json"));
    }
}

Output

true
false

Run this on your computer — see “Get Started” for setup.

Filter by extension
public class Main {
    public static void main(String[] args) {
        String[] files = {"report.pdf", "photo.png", "notes.pdf"};
        for (String f : files) {
            if (f.endsWith(".pdf")) System.out.println(f);
        }
    }
}

Output

report.pdf
notes.pdf

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?