Java String endsWith() method
It is a predefined function which is present in the Java.lang.String package. It is used to check whether your string ends with the specific sequence of characters or not (suffix) which you will pass actually in the parameter of this method and returns boolean type, true if it starts with the string passed or false if it is not starts with the string passed.
Syntax of endsWith() method
public boolean endsWith(String suffix) {}
Example 01 of endsWith(String suffix) method
public class EndsWith {
public static void main(String[] args)
{
String s1="Harry Porter";
System.out.println(s1.endsWith("er"));
System.out.println(s1.endsWith("ter"));
System.out.println(s1.endsWith("Porter"));
System.out.println(s1.endsWith("Harry"));
}
}
Output:
true
true
true
false
Example 02 of endsWith(String suffix) method
program 01: "To check whether a user entered string suffix(ending part of string) is matches with the suffix of already defined string or not".
Problem Statement: "First define any one string in your program and takes another string input form user and checks whether the suffix of user entered string is matches with the suffix of already defined string or not, if it matches print yes, and if no then, give another chance to user to enter the string again repeatedly till the suffix of user entered string is matches with the suffix of already defined string, when it matches print yes and terminate the code".
import java.io.*;
public class EndsWith {
public static void main(String[] args) throws IOException
{
System.out.println("enter the ending string as your wish to check whether the string that is already defined is ends with this prefix string you entered or not");
checkToEndsWith();
}
public static void checkToEndsWith() throws IOException
{
String s1="Harry Porter";
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
String s2 = b.readLine();
if(s2.endsWith("Porter") || s2.endsWith("r") || s2.endsWith("e") || s2.endsWith("t") || s2.endsWith("r") || s2.endsWith("o") || s2.endsWith("p") || s2.endsWith("er") || s2.endsWith("ter") || s2.endsWith("rter") || s2.endsWith("orter"))
{
System.out.println("yes absolutely");
}
else
{
System.out.println("no");
System.out.println("try again");
checkToEndsWith();
}
}
}
Output:
enter the ending string as your wish to check whether the string that is already defined is ends with this prefix string you entered or not
marvel
no
try again
dany
no
try again
iron man
no
try again
natasha romanoff
no
try again
captain marvel
no
try again
dr.strange
yes absolutely
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.