String.startsWith()
Checks whether a string starts with the given prefix.
Available since: Java 1.0
Syntax
public boolean startsWith(String prefix)Parameters
| Parameter | Type | Description |
|---|---|---|
| prefix | String | The 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
falsePicking lines by a prefix:
void main() {
String[] lines = {"# title", "text", "# note"};
for (String line : lines) {
if (line.startsWith("#")) {
IO.println(line);
}
}
}Output:
# title
# noteNotes
The check is case-sensitive. There is a version with an offset: startsWith("lo", 3) checks the text starting at index 3.
See also
- String.endsWith() — Checks whether a string ends with the given suffix.
- String.contains() — Checks whether a string contains a substring.
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.