Unlocking the Power of Java’s endsWith() Method

Understanding the Syntax

The endsWith() method is a part of the String class, and its syntax is straightforward.

public boolean endsWith(String str)

The method takes a single parameter, str, which is the string you want to check against. The method returns a boolean value, indicating whether the original string ends with the specified str or not.

How it Works

The endsWith() method is case-sensitive, meaning it treats upper-case and lower-case characters differently. This is demonstrated in the example below:


String str = "Hello World";
System.out.println(str.endsWith("World")); // returns true
System.out.println(str.endsWith("world")); // returns false

As you can see, the method accurately identifies whether the string ends with the specified sequence, taking into account the case of the characters.

Beyond endsWith(): Exploring Other String Methods

While endsWith() is a valuable tool, it’s not the only string method at your disposal.

If you need to check whether a string begins with a specific sequence, you can use the startsWith() method. This method works similarly to endsWith(), but checks the beginning of the string instead.


String str = "Hello World";
System.out.println(str.startsWith("Hello")); // returns true
System.out.println(str.startsWith("hello")); // returns false

Other useful string methods include:

  • contains(): checks if a string contains a specified sequence of characters
  • indexOf(): returns the index of the first occurrence of a specified character or substring
  • lastIndexOf(): returns the index of the last occurrence of a specified character or substring

By mastering these string methods, you’ll be better equipped to tackle complex string manipulation tasks in Java.

Leave a Reply