Java String.endsWith() Method Example

1. Introduction

The String.endsWith() method in Java is used to check if a given string ends with the specified suffix. This method returns a boolean value: true if the string ends with the suffix, otherwise false. This tutorial will show you how to use the endsWith() method with a simple example.

Key Points

- The endsWith() method checks if the string ends with the specified suffix.

- It returns a boolean value.

- This method is case-sensitive.

2. Program Steps

1. Declare a string.

2. Specify a suffix to check.

3. Use the endsWith() method to check if the string ends with the given suffix.

4. Print the result.

3. Code Program

public class StringEndsWithExample {
    public static void main(String[] args) {
        // Declare the String
        String str = "Hello, world!";
        // Specify the suffix to check
        String suffix = "world!";
        // Check if the string ends with the specified suffix
        boolean result = str.endsWith(suffix);
        // Print the result
        System.out.println("Does the string end with '" + suffix + "'? " + result);
    }
}

Output:

Does the string end with 'world!'? true

Explanation:

1. String str = "Hello, world!": Declares and initializes a String variable str.

2. String suffix = "world!": Specifies the String variable suffix that we want to check if str ends with.

3. boolean result = str.endsWith(suffix): Uses the endsWith() method to determine if str ends with the suffix.

4. System.out.println("Does the string end with '" + suffix + "'? " + result): Prints whether str ends with suffix.


Comments