C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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