Home
Java
String startsWith and endsWith Methods
Updated Oct 8, 2023
Dot Net Perls
StartsWith. A string has special characters at its start. In Java, we can test those characters with startsWith. This tests the string and returns true or false.
And with endsWith, we can test the end part of a string. We can use these methods on any string. We can even loop over a string array and test each string.
StartsWith example. Here we use the startsWith method. We call startsWith several times on a single string, and then print values based on the results.
Argument 1 We call startsWith with one argument—here the string starts with "cat" so "true" is printed.
Argument 2 The second argument to the startsWith method is an int. This is the offset. The "starting" string is checked for at this index.
Finally We invoke startsWith but the argument is not found in the string. StartsWith here returns false.
public class Program { public static void main(String[] args) { String value = "cat and dog"; if (value.startsWith("cat")) { // The string starts with cat. System.out.println(true); } if (value.startsWith("and", 4)) { // The string has and at the offset 4. System.out.println(true); } if (value.startsWith("bird")) { // The string does not start with bird. System.out.println(false); // Not reached. } } }
true true
EndsWith example. Let us test endsWith. We create a string array of three strings. Then we call endsWith on all three elements in the array.
Result The strings "cat" and "flat" end with the string "at." The string "bird" does not.
Note The endsWith method cannot accept an offset. We can only test the absolute end of a string.
public class Program { public static void main(String[] args) { String[] array = { "cat", "flat", "bird" }; // Loop over string array. for (String value : array) { // See if string ends with "at" substring. if (value.endsWith("at")) { System.out.println(value); } } } }
cat flat
An alternative. With charAt we can check any char within a string at an index. For simple tests, we can use charAt instead of startsWith and endsWith.
String charAt
Review. StartsWith and endsWith are useful methods. With startsWith we can specify an offset where checking should begin. We can check strings, or an entire array of strings.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 8, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen