String methods – startsWith and endsWith
In this post, we will discuss 2 methods which are endsWith() and startsWith().
Let’s understand with examples.
boolean endsWith(String suffix):
This method checks if string ends with specified suffix. If ends with specified suffix then returns true else false.
public class StringMethodsEx { public static void main(String[] args) { String val1 = "Hello world!!"; System.out.println(val1.endsWith("!!")); //returns true System.out.println(val1.endsWith("World")); //returns false } }
true
false
startswith() :
This method returns true if string starts with specified prefix, else will return false. It has 2 types of implementations.
1. boolean startsWith(String prefix):
It checks if string starts with specified prefix or not.
public class StringMethodsEx { public static void main(String[] args) { String val1 = "Hello world!!"; System.out.println(val1.startsWith("Hello")); //returns true System.out.println(val1.endsWith("World")); //returns false } }
true
false
boolean startsWith(String prefix,int toffset):
This method returns true if string starts with specified prefix starting from the given index.
public class StringMethodsEx { public static void main(String[] args) { String val1 = "Hello world!!"; System.out.println(val1.startsWith("Hello", 0)); //returns true System.out.println(val1.startsWith("Hello",4)); //returns false as Hello string start at 0 } }
true
false