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

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.