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
exampleHere we use the startsWith
method. We call startsWith
several times on a single string
, and then print values based on the results.
startsWith
with one argument—here the string
starts with "cat" so "true" is printed.startsWith
method is an int
. This is the offset. The "starting" string
is checked for at this index.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
exampleLet us test endsWith
. We create a string
array of three strings. Then we call endsWith
on all three elements in the array.
string
"at." The string
"bird" does not.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
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
.
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.