Ticker

6/recent/ticker-posts

String endsWith() Method in Java

String endsWith() Method in Java

Overview

The endsWith() method in Java is a built-in string method that allows you to check whether a given string ends with a specific suffix. It returns a boolean value indicating whether the original string ends with the provided suffix or not.

Syntax

java
public boolean endsWith(String suffix)

Parameters

  • suffix: The suffix to check at the end of the string.

Return Value

  • true if the string ends with the specified suffix.
  • false if the string does not end with the specified suffix.

Example 1: Using endsWith() Method

java
public class EndsWithExample {
public static void main(String[] args) {
String str1 = "Hello, World!";
String suffix1 = "World!";
String suffix2 = "Java";

// Check if str1 ends with suffix1
boolean endsWithSuffix1 = str1.endsWith(suffix1);
System.out.println("str1 ends with suffix1: " + endsWithSuffix1);

// Check if str1 ends with suffix2
boolean endsWithSuffix2 = str1.endsWith(suffix2);
System.out.println("str1 ends with suffix2: " + endsWithSuffix2);
}
}

Explanation

In the above example, we have a string str1 containing the value "Hello, World!". We then use the endsWith() method to check if str1 ends with two different suffixes, "World!" and "Java".

The first call to endsWith() checks if str1 ends with "World!". Since "Hello, World!" does end with "World!", the result is true, which is stored in the variable endsWithSuffix1.

The second call to endsWith() checks if str1 ends with "Java". As "Hello, World!" does not end with "Java", the result is false, and it is stored in the variable endsWithSuffix2.

The program then prints out the results, demonstrating the usage and functionality of the endsWith() method in Java.

Remember that the endsWith() method is case-sensitive, so make sure to provide the correct suffix in the same case as the original string's characters to get accurate results.

Post a Comment

0 Comments