Java Reference ยท java.lang
Java String.startsWith() and endsWith() methods
Reference for Java String.startsWith() and endsWith(): test prefixes and suffixes, use an offset, and learn about case sensitivity and null.
startsWith() tells you whether a string begins with a given prefix, and endsWith() tells you whether it finishes with a given suffix. Both return a boolean and never change the string. They are the right tool for checking file extensions, URL schemes, command prefixes and similar "does it look like this" questions.
The comparison is exact and case-sensitive, and it compares UTF-16 code units. There is a second form of startsWith() that begins the comparison at an index of your choice.
boolean isPdf = "report.pdf".endsWith(".pdf"); // true boolean isHttp = "https://example.org".startsWith("http"); // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public boolean startsWith(String prefix) public boolean startsWith(String prefix, int toffset) public boolean endsWith(String suffix)
| Name | Description |
|---|---|
prefix |
The text the string should begin with. |
toffset |
The index in this string where the comparison starts. |
suffix |
The text the string should end with. |
Returns: true if the string (from toffset for the two-argument form) begins with prefix, or ends with suffix; otherwise false.
Throws: NullPointerException if the argument is null (or if the string you call it on is null).
Usage notes
- Case-sensitive. There is no
startsWithIgnoreCase(). UseregionMatches(true, 0, prefix, 0, prefix.length()), or compare lower-cased copies with a fixedLocale. - The empty string matches.
s.startsWith("")ands.endsWith("")are alwaystrue, so validate empty input yourself if that matters. - Out-of-range offsets give
false, not an exception. A negativetoffset, or one greater thanlength(), simply returnsfalse. endsWith()has no offset form. To test a suffix of a shorter part of the string, callsubstring()first or useregionMatches().- Not a regex. The argument is literal text;
"a.b".startsWith("a.")istrueand.has no special meaning. For patterns usematches(). - Speed. Both methods compare at most
prefix.length()characters, so they are cheap and do not allocate. - For paths, prefer
Path.Path.startsWith()compares whole path elements, which avoids"/data-old".startsWith("/data")surprises.