Java String endsWith() method example

Java String endsWith() method is used to check the suffix of the string. It verifies if given string ends with argument string or not.

1. Java String endsWith(String str) method

Java program to check if a string ends with suffix argument string 'str'.

public class Main 
{
    public static void main(String[] args) 
    {
        String blogName = "howtodoinjava.com";
        
        System.out.println( blogName.endsWith("com") );  //true
        
        System.out.println( blogName.endsWith("net") );  //false
    }
}

Program output.

true
false

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

1.1. ‘null’ method argument is not allowed

Please note that null is not allowed as method argument to endsWith() method. It will throw NullPointerException if null is passed.

public class StringExample 
{
    public static void main(String[] args) 
    {
    	String blogName = "howtodoinjava.com";
        
        System.out.println( blogName.endsWith(null) );
    }
}

Program output.

Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.endsWith(String.java:1436)
	at com.StringExample.main(Main.java:11)

Reference:

Java String Doc

Leave a Reply

0 Comments
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