In Java, startsWith() returns true when a string begins with the given prefix, and false otherwise. The comparison is exact and case-sensitive.
The second overload checks the prefix at a chosen offset instead of index 0, which is handy for fixed-format text such as "ID:12345". It is the mirror image of endsWith().
startsWith() is an instance method of java.lang.String, available since JDK 1.0. Call it on a string, as in text.startsWith(...); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed.
Syntax
Pass the prefix, and optionally the index where it should appear.
java
boolean secure = url.startsWith("https://");
boolean comment = line.startsWith("#");
boolean code = record.startsWith("12", 3); // "12" at index 3?
Call
What it does
"Java".startsWith("Ja")
true.
"Java".startsWith("ja")
false: case matters.
"Java".startsWith("va", 2)
true: "va" starts at index 2.
"Java".startsWith("")
true: every string starts with the empty string.
s.startsWith(p, k) gives the same answer as s.substring(k).startsWith(p) for a valid k, but creates no new string and returns false (instead of throwing) when k is negative or larger than the length.
Library declarations
java
public boolean startsWith(String prefix);
public boolean startsWith(String prefix, int toffset);
Parameters
Parameter
Description
prefix
The text the string should begin with. Must not be null.
toffset
Optional. The index where the prefix should start. Defaults to 0.
Return Value
Return Value
Description
true
The characters at the offset equal the prefix (always true for an empty prefix at a valid offset).
false
Otherwise, including when the offset is out of range.
Java Examples
Example 1 — Check Whether a URL Uses HTTPS
Test three addresses against the same prefix, including one written in capitals.
java
public class StartsWithUrl {
public static void main(String[] args) {
String[] urls = {"https://codetofun.com", "http://old.example", "HTTPS://LOUD.EXAMPLE"};
for (String url : urls) {
System.out.println(url + " secure? " + url.startsWith("https://"));
}
}
}