Java String endsWith() Method

Java String EndWiths () Method

What is String?

In Java, an string class is a series of characters that are interpreted literally by a script. Character strings are represented by the String class. Java programs implement “abc” and other string literals as instances of this class.

  • Numerous methods, including compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), and substring(), are available in the Java String class.

To know more about String Class in java read the complete article.

String endsWith() Method:

The Java String endsWith() method is used to know if the string ends with the user-specified substring or not.If the string ends with the specified suffix, it returns true; otherwise, it returns false.

  • The java.lang.String class provides a lot of built-in methods that are used to manipulate string in Java.These methods help us to perform operations on String objects such as trimming, concatenating, converting, comparing, replacing strings etc.

Syntax:

public boolean endsWith(String suffix)

Parameters:

suffix - the suffix.

Let’s look at a string-related Java program where the Java String endsWith() method is used to perform an operation on the given string.

Example :Taking two strings str1 and str2 and we are checking whether the strings are ending with the specified suffixes.

Run
public class Main {
  public static void main(String[] args) {
    String myStr = "Hello PrepInsta";
    System.out.println(myStr.endsWith("sta"));
    System.out.println(myStr.endsWith("Insta"));
    System.out.println(myStr.endsWith("Hello"));
  }
}

Output

true
true
false

Example 2 : Taking two strings str1 and str2 and we are checking whether the strings are ending with the specified suffixes.

Run
public class Main {
    public static void main(String[] args) {
        String message = "Happy New Year 2023";
        System.out.println(message.endsWith("2023"));
        System.out.println(message.endsWith("2022"));
    }
}

Output

true
false

Examples 3: Taking two strings str1 and str2 and we are checking whether the strings are ending with the specified suffixes.

Run
public class Main {
  public static void main(String[] args) {
    String myStr = "PrepInsta prime is like netflix";
    System.out.println(myStr.endsWith("prime"));
    System.out.println(myStr.endsWith("flix"));
    System.out.println(myStr.endsWith("PrepInsta"));
  }
}  

Output

false
true
false

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription