Java: String endsWith(String suffix) method

In this article, we will discuss how to test whether a string ends with particular character sequence (another string or suffix) using String’s endsWith() method

 

endsWith(String suffix) method: This String method tests whether invoking string ends with specified/supplied suffix

 

Method Signature:

public boolean endsWith(String suffix);

 

Returns:

Returns a boolean value either true or false

  • True –> if invoking string ends with string suffix (supplied/passed as argument)
  • False –> if invoking string doesn’t ends with string suffix (supplied/passed as argument)

 

Examples on endsWith() method:

Below demo program examines whether invoking string ends with specified suffix

StringEndsWithMethod.java

package in.bench.resources.string.methods;

public class StringEndsWithMethod {

	public static void main(String[] args) {

		String str1 = "German Siemens";
		String str2 = new String("Team BenchResources.Net");

		// checking with string literal
		boolean bool1 = str1.endsWith("mens");

		// printing to the console
		System.out.println("Whether str1 endsWith mens : " + bool1);

		// checking with string literal
		boolean bool2 = str2.endsWith("Net");

		// printing to the console
		System.out.println("Whether str2 endsWith Net : " + bool2);

		// case false: not endsWith
		System.out.println("Whether str1 endsWith Bench : " 
                                          + str1.endsWith("Bench"));
	}
}

Output:

Whether str1 endsWith mens : true
Whether str2 endsWith Net : true
Whether str1 endsWith Bench : false

 

References:

https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
https://docs.oracle.com/javase/tutorial/java/data/strings.html
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

 

Happy Coding !!
Happy Learning !!