Java String endsWith()

Java String.endsWith() is used to check the suffix of a given string. It verifies if the given string ends with the argument string or not. To check if a string starts with a specified substring, use startsWith() method.

Note that using the regular expression is also an effective way to check if the given string ends with the specified pattern.

1. String.endsWith() API

The endsWith() method takes one string argument and checks if the argument string is present at the end of this string.

public boolean endsWith(String suffix);

The method returns a boolean value indicating:

  • true – the string ends with the specified character(s)
  • false – the string does not end with the specified character(s)

2. Regular Expressions are Not Supported

String endsWith() does not accept the regular expression as the method argument. If we pass the regex pattern as the argument, it will only be treated as a normal string.

Assertions.assertFalse( name.endsWith("java$") );

3. NULL is Not Allowed

The null is not allowed as a method argument, and any such attempt will throw NullPointerException.

Assertions.assertThrows(NullPointerException.class, ()->{

Reference: Java String Doc


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode