Java startsWith and endsWith Methods

Use the startsWith and endsWith string methods. These methods test leading and trailing chars.
StartsWith. A string has special characters at its start. We can test those characters with startsWith. This tests the string and returns true or false.Strings
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.
First example. Here we use the startsWith method. We call startsWith with one argument—here the string starts with "cat" so "true" is printed.

Offset: 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.

Java program that uses startsWith method 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. } } } Output 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.

Java program that uses endsWith 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); } } } } Output 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.charAt
A 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls