Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Check the End of a String in Java



In general, the endswith() method in Java is used to check whether the given string ends with a specific suffix string or not. If the substring ends with the specific string then it will return a Boolean value true, otherwise it will return false if the value is not found.

Syntax
public boolean endsWith(String suffix)

Problem Statement

Write a program to check if a string ends with a specific substring in Java ?

Input

str = demo

Output

The string ends with the word mo

Step to check the end of a string

Following are the steps to check with a specific substring ?

  • Start
  • Create a string.
  • Use the endsWith() method to see if the string ends with the desired substring.
  • Implement an if-else conditional statement to print appropriate messages based on the result.
  • Stop

Java program to check the end of a string

Below is the Java program to check the end of a string ?

public class Demo {
    public static void main(String[] args) {
       String str = "demo";
       if(str.endsWith("mo")) {
          System.out.println("The string ends with the word mo");
       } else {
          System.out.println("The string does not end with the word mo");
       }
    }
}

Output

The string ends with the word mo

Code explanation

Let's say the following is our string ?

String str = "demo";

Now, check for the substring "mo" using the endsWith() method in an if-else condition.

if(str.endsWith("mo")) {
 System.out.println("The string ends with the word mo");
} else {
 System.out.println("The string does not end with the word mo");
}

In this article, we learned how to use the endsWith() method in Java to check string endings.

Updated on: 2024-08-02T18:17:40+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements