The String.startsWith() method checks whether a string begins with a specified prefix, returning a boolean result (true or false).
Prefix Testing & Offset Anchors: Java supports checking from index 0 or from an arbitrary offset index. To verify trailing suffixes, explore endsWith(). For substring presence anywhere, see contains(). For index coordinate extraction, see indexOf(), or slice text with substring().
Java provides two overloaded methods in java.lang.String to support prefix testing:
// 2 Overloaded signatures of startsWith() in java.lang.String
public boolean startsWith(String prefix)
public boolean startsWith(String prefix, int toOffset)
| Signature | Parameters | Operational Behavior |
|---|---|---|
startsWith(String prefix) |
prefix (String) |
Tests whether the string begins with prefix at index 0. |
startsWith(String prefix, int toOffset) |
prefix, toOffset (int) |
Tests whether the sub-sequence starting at index toOffset begins with prefix. |
Testing prefixes confirms whether a string opens with a specific character sequence:
String my_str = "plus2net";
System.out.println(my_str.startsWith("plus")); // true
System.out.println(my_str.startsWith("pl")); // true
System.out.println(my_str.startsWith("p")); // true
System.out.println(my_str.startsWith("plus2net")); // true
System.out.println(my_str.startsWith("PLUS")); // false (case-sensitive)
System.out.println(my_str.startsWith("net")); // falseTerminal Output:
true
true
true
true
false
false
The toOffset parameter allows checking for prefixes starting at arbitrary interior positions without creating a temporary substring:
String url = "https: // www.plus2net.com";
// 1. Check from index 0
System.out.println(url.startsWith("https")); // true
// 2. Check from index 8 (past "https://")
System.out.println(url.startsWith("www", 8)); // true
// 3. Check from index 12 (past "https://www.")
System.out.println(url.startsWith("plus2net", 12)); // true
// 4. Invalid offset safely returns false (no exception thrown)
System.out.println(url.startsWith("plus", 50)); // falseTerminal Output:
true
true
true
false
Choosing the right inspection method depends on where the target pattern is expected to appear:
| Method | Anchor Location | Primary Use Case |
|---|---|---|
str.startsWith(prefix) |
Beginning (index 0 or toOffset). |
Protocols (https://), command flags (--), path roots (/). |
str.endsWith(suffix) |
Trailing end (length() - 1). |
File extensions (.pdf), domain TLDs (.com). |
str.contains(seq) |
Anywhere inside string. | Keyword search, moderation filters, token presence. |
startsWith() is strictly case-sensitive. You can normalize with toLowerCase(), or use regionMatches() for zero memory allocation:
String filename = "README.md";
String prefix = "readme";
// 1. Direct check: Case-sensitive (returns false)
System.out.println("Direct startsWith: " + filename.startsWith(prefix)); // false
// 2. Approach A: toLowerCase() normalization
boolean approachA = filename.toLowerCase().startsWith(prefix.toLowerCase());
System.out.println("toLowerCase check: " + approachA); // true
// 3. Approach B: regionMatches() (Zero heap allocations!)
boolean approachB = filename.regionMatches(true, 0, prefix, 0, prefix.length());
System.out.println("regionMatches check: " + approachB); // trueTerminal Output:
Direct startsWith: false
toLowerCase check: true
regionMatches check: true
Passing null as the prefix immediately throws a NullPointerException. Guard against crashes with null checks:
String document = "invoice-2026.pdf";
String query = null;
// RISKY: Passing null throws NullPointerException
try {
System.out.println(document.startsWith(query));
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException on null prefix!");
}
// SAFE APPROACH: Guard against null before calling
boolean safe = (document != null && query != null) && document.startsWith(query);
System.out.println("Safe check result: " + safe);Terminal Output:
Caught NullPointerException on null prefix!
Safe check result: false
Validating whether an address uses a secure web protocol before routing network connections:
public class UrlValidator {
public static boolean isSecureWebUrl(String url) {
if (url == null) return false;
return url.startsWith("https: // ");
}
public static void main(String[] args) {
System.out.println("https link: " + isSecureWebUrl("https: // www.plus2net.com")); // true
System.out.println("http link: " + isSecureWebUrl("http: // example.com")); // false
System.out.println("ftp link: " + isSecureWebUrl("ftp: // files.example.com")); // false
}
}Terminal Output:
https link: true
http link: false
ftp link: false
Differentiating between short flags (-h), long flags (--verbose), and regular arguments:
String[] arguments = {"--verbose", "--output=report.pdf", "-h", "input.txt"};
for (String arg : arguments) {
if (arg.startsWith("--")) {
System.out.println("Long option flag: " + arg);
} else if (arg.startsWith("-")) {
System.out.println("Short option flag: " + arg);
} else {
System.out.println("Positional argument: " + arg);
}
}Terminal Output:
Long option flag: --verbose
Long option flag: --output=report.pdf
Short option flag: -h
Positional argument: input.txt
str.startsWith("") returns true for any non-null string, provided 0 <= toOffset <= length(). Be careful when validating user inputs against empty filter strings.
Unlike charAt() or substring() which throw out-of-bounds exceptions, startsWith(prefix, toOffset) safely returns false if toOffset < 0 or toOffset > length().
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringStartsWithFullDemo {
public static void main(String[] args) {
String filepath = "/home/user/docs/resume.pdf";
// 1. Verify root path prefix
if (filepath.startsWith("/")) {
System.out.println("Check 1 Passed: Path starts with root slash.");
}
// 2. Verify offset prefix matching
int docsIndex = filepath.indexOf("docs");
if (filepath.startsWith("docs", docsIndex)) {
System.out.println("Check 2 Passed: 'docs' verified at offset " + docsIndex + ".");
}
// 3. Verify empty string behavior (always true)
if (filepath.startsWith("")) {
System.out.println("Check 3 Passed: Empty prefix returned true.");
}
System.out.println("All String.startsWith() verification tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Path starts with root slash.
Check 2 Passed: 'docs' verified at offset 11.
Check 3 Passed: Empty prefix returned true.
All String.startsWith() verification tests passed successfully!
No. startsWith() strictly expects a String. Pass the character as a string: str.startsWith("p") or check str.charAt(0) == 'p'.
If prefix.length() > str.length(), startsWith() immediately returns false without throwing an error.
Yes. startsWith() only checks characters up to the length of the prefix and stops immediately on first mismatch, whereas indexOf() may scan further if misused.
No. startsWith() searches for literal character sequences. For regex pattern matching, use str.matches("^pattern.*").
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.