Home » Java String endsWith() method

Java String endsWith() method

by Online Tutorials Library

Java String endsWith()

The Java String class endsWith() method checks if this string ends with a given suffix. It returns true if this string ends with the given suffix; else returns false.

Signature

The syntax or signature of endsWith() method is given below.

Parameter

suffix : Sequence of character

Returns

true or false

Internal implementation

The internal implementation shows that the endWith() method is dependent on the startsWith() method of the String class.

Java String endsWith() Method Example

FileName: EndsWithExample.java

Test it Now

Output:

true  true  

Java String endsWith() Method Example 2

Since the endsWith() method returns a boolean value, the method can also be used in an if statement. Observe the following program.

FileName: EndsWithExample2.java

Output:

false  String ends with .com  

Java String endsWith() Method Example 3

The endsWith() method takes care of the case sensitiveness of the characters present in a string. The following program shows the same.

FileName: EndsWithExample3.java

Output:

false  false  true  

Java String endsWith() Method Example 4

When an empty string is passed in the parameter of the method endsWith(), the method always returns a true value. The reason behind this is that a string never changes when we append an empty string to it. For example,

The statement

results in

str = “Ladies and Gentlemen”;

Thus, we can say that any string in Java ends with an empty string (“”). Observe the

FileName: EndsWithExample4.java

Output:

true  false  

Java String endsWith() Method Example 5

The endsWith() method raises the NullPointerException if one passes null in the parameter of the method. The following example shows the same.

FileName: EndsWithExample5.java

Output:

Exception in thread "main" java.lang.NullPointerException  at java.base/java.lang.String.endsWith(String.java:1485)  at EndsWithExample5.main(EndsWithExample5.java:9)  

Java String endsWith() Method Example 6

A String literal can also call the endsWith() method. The following program shows the same.

FileName: EndsWithExample6.java

Output:

Inside the if block  Inside the if block  Inside the else block  

You may also like