Java String endsWith() example

In this guide, you will learn about the String endsWith() method in Java programming and how to use it with an example.

1. String endsWith() Method Overview

Definition:

The endsWith() method in Java's String class is used to check if the string ends with a specified suffix.

Syntax:

str.endsWith(suffix)

Parameters:

- suffix: The ending substring which we are checking if the string ends with.

Key Points:

- This method returns true if the character sequence represented by the argument is a suffix of the character sequence represented by the string object; otherwise, it returns false.

- It's case-sensitive. For instance, "Hello" and "hello" are considered different suffixes.

- If the suffix is an empty string, the method will always return true.

- No exception is thrown even if suffix is null, but the program might encounter a runtime exception.

2. String endsWith() Method Example

public class EndsWithExample {
    public static void main(String[] args) {
        String sample = "Java Programming";

        // Checking if the string ends with a certain sequence
        boolean endsWithJava = sample.endsWith("Java");
        System.out.println("Does the sample end with 'Java'? " + endsWithJava);

        // Checking with the correct ending sequence
        boolean endsWithProgramming = sample.endsWith("Programming");
        System.out.println("Does the sample end with 'Programming'? " + endsWithProgramming);

        // Attempting to check with a null suffix
        try {
            sample.endsWith(null);
        } catch (Exception e) {
            System.out.println("Error: Cannot check with a null suffix.");
        }
    }
}

Output:

Does the sample end with 'Java'? false
Does the sample end with 'Programming'? true
Error: Cannot check with a null suffix.

Explanation:

In the example, we first check if the string "Java Programming" ends with the substring "Java", which it doesn't, so the output is false

Next, we check if it ends with "Programming", which is true. Then, we intentionally check with a null suffix to see how the program responds. A runtime exception occurs, which is caught and handled by printing an appropriate error message.

Related Java String Class method examples

Comments