Home
Map
String startsWith and endsWith MethodsUse the startsWith and endsWith string methods. These methods test leading and trailing chars.
Java
This page was last reviewed on Oct 8, 2023.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 8, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.